如何在ASP.NET中使用C#从数据库中检索二进制图像

Liu*_*Hui 3 c# sql-server asp.net image

我需要从数据库中检索二进制图像.

我的疑问如下.

SqlConnection con = new SqlConnection(@"Data Source=localhost;Initial Catalog=MyGames;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select blueBallImage from CorrespondingBall WHERE objective = Default Ball", con);
Run Code Online (Sandbox Code Playgroud)

我不知道如何检索作为二进制图像的blueBallImage.

成功检索后,我需要使用包含文本的下拉列表在图像上添加文本.代码如下.

Bitmap bmp = new Bitmap(@"C:\Users\apr13mpsip\Documents\Visual Studio 2012\WebSites\CorrespondingBallWebSite\Images\blueBallDefault.png");
Run Code Online (Sandbox Code Playgroud)

目前,我不知道如何检索图像.因此,我硬编码了我不想要的东西.我想从数据库中检索它.

Graphics gra = Graphics.FromImage(bmp);

gra.DrawString(ddlCharacter.Text, new Font("Verdana", 18), Brushes.Black, new PointF(4, 6));

MemoryStream ms1 = new MemoryStream();
bmp.Save(ms1, ImageFormat.Png);
var base64Data = Convert.ToBase64String(ms1.ToArray());
imgImage.ImageUrl = "data:image/png;base64," + base64Data;
Run Code Online (Sandbox Code Playgroud)

Meh*_*ard 6

这是从数据库快速加载图像并加载到ASP中的html图像源的基本示例.请告诉我它是否适合你;-)

//Get byte array from image file in the database with basic query
SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select [logo] FROM [dbo].[tblCompanyInfo]", GlobalUser.currentConnectionString);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    // Get the byte array from image file
    byte[] imgBytes = (byte[]) row["logo"];

    // If you want convert to a bitmap file
    TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
    Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes);

    string imgString = Convert.ToBase64String(imgBytes);
    //Set the source with data:image/bmp
    imgLogoCompany.Src = String.Format("data:image/Bmp;base64,{0}\"", imgString);
}
Run Code Online (Sandbox Code Playgroud)