将字节从sql server渲染到图像控件?

标记:

  

代码隐藏:

 public void ProcessRequest(HttpContext context) { //write your handler implementation here. string username = Convert.ToString(context.Request.QueryString["username"]); if (username != null) { DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(); byte[] arrContent; DataRow dr; string strSql; strSql = "Select Image from GalleryImages where username = '" + username + "'"; da = new SqlDataAdapter(strSql, connection.ConnectionString); da.Fill(ds); dr = ds.Tables[0].Rows[0]; arrContent = (byte[])dr["ImageFile"]; context.Response.ContentType = "jpeg"; context.Response.OutputStream.Write(arrContent, 0, arrContent.Length); context.Response.End(); } } 

我还在web.config中添加了httphandlers部分。 但是我没有在ListView控件中获取图像。

很酷的问题。 我会编写一个实现IHttpHandler的类来响应对图像文件的请求。

有关如何在SQL varbinary(max)字段中输入和输出文件流的示例,请参阅以下问题中的答案。

如何在ASP.NET中创建fileupload接口

在制作HTTP响应时,不要忘记使用正确的MIME类型。

您必须创建一个返回图像的http处理程序

 public void ProcessRequest(HttpContext context) { byte[] yourImage = //get your image byte array context.Response.BinaryWrite(yourImage); context.Request.ContentType = "image/jpeg"; context.Response.AddHeader("Content-Type", "image/jpeg"); context.Response.AddHeader("Content-Length", (yourImage).LongLength.ToString()); con.Close(); context.Response.End(); context.Response.Close(); } 

您可以通过从visual studio创建GenericHandler文件类型并添加之前的代码然后调用您可以将通用处理程序的url写为图像源来实现

在这里查看全文。

 public class NWEmpPhotoHandler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext ctx) { string id = ctx.Request.QueryString["id"]; SqlConnection con = new SqlConnection(<>); SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID = @EmpID", con); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@EmpID", id); con.Open(); byte[] pict = (byte[])cmd.ExecuteScalar(); con.Close(); ctx.Response.ContentType = "image/bmp"; ctx.Response.OutputStream.Write(pict, 78, pict.Length - 78); } } 

通过ASP.Net MVC从SQL Server下载和上载图像 。

代码是MVC,但实现背后的想法不是MVC特定的,可以在通用ASP中使用。 问题的关键是你要避免将数据库BLOB读入字节数组,然后将字节数组写入响应中,这样做会导致加载时性能不佳,因为许多大型数组分配(图像可以容易进入2 MB +,大图像可以达到数十甚至数百MB)。 本文介绍如何执行基于流的实现,其中字节在从数据库读取时发送回HTTP响应。