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

2024-01-11

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

我的疑问如下。

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);

我不知道如何检索二值图像 blueBallImage。

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

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

我暂时不知道如何检索图像。因此,我对它进行了硬编码,这是我不想要的。我想从数据库中检索它。

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;

下面是一个基本示例,用于快速从数据库加载图像并加载到 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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