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

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

我的查询如下。

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

你需要创建一个ASP.NET处理程序(* .ASHX)来提供图像的字节

  

在图像处理程序中,您需要像这样编码

 public class ImageHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { // Load the image (see previous code sample) byte[] data = Convert.FromBase64String(encodedString); // Display the image context.Response.OutputStream.Write(data, 0, data.Length); context.Response.ContentType = "image/JPEG"; } } 

请参考以获取更多信息来自数据库的图片

 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Connect(); } try { cm = new SqlCommand("select profile_pic from TblNewMemberRegistration where user_name='sudhanshu@mailbox.com'", cn); byte[] b = (byte[])cm.ExecuteScalar(); stream.Write(b, 0, b.Length); Bitmap bm = new Bitmap(stream); Response.ContentType = "image/gif"; bm.Save(Response.OutputStream, ImageFormat.Gif); } catch(Exception ex) { Response.Write(ex.Message); } finally { cn.Close(); stream.Close(); } } protected void Connect() { cn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString); cn.Open(); }