C#读取数据库字节流生成图片
前台用DataList绑定
<asp:DataList ID="DataList1" runat="server"> <ItemTemplate> <asp:Label ID="lbNwes" runat="server" Text='<%#Eval("Id")%>'></asp:Label> <a href="<%# "ImageHandler.ashx?ImID="+ Eval("mainid") %>" target="_blank" title="点击放大看"> <asp:Image ID="Image1" Width="100px" Height="100px" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("mainid") %>' /> </a> <asp:Image ID="Image2" runat="server" Width="100px" Height="100px" /> </ItemTemplate> </asp:DataList>
后台用ImageHandler.ashx处理程序处理数据,代码如下:
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/gif"; string imageid = context.Request.QueryString["ImID"]; byte[] MyData = new byte[0]; using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strconn"].ConnectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "select Data from Blobs where mainid=" + imageid; SqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); MyData = (byte[])sdr["Data"]; context.Response.BinaryWrite(MyData); } }
这样能实现图片绑定到DataList上,但有一个问题,当有100个图片时,必须发出100个请求。载图如下,希望有好的方法分享一下。