显示图像中的GridView从数据库?

问题描述:

我保存在SQL Server数据库作为二进制数据的图像。现在,我要显示在GridView这些图像。但是,网络控制,直接从数据库中读取数据。 Web图像控制要求的ImageUrl 属性,以便为我的图片是在数据库中不能使用此。不过,我可以存储一个文件夹中的图片,但我想直接从一个网格数据库并显示读取的图像数据的一些不同的方式。

I have images saved in SQL server database as a binary data. Now I want to show these images in the Gridview. But there web control which directly read the data from the database. Web image control requires ImageUrl property so can not use this as my images are in databases. However i can store the images in a folder but i want some different way which directly read image data from the database and show in a grid.

使用通用处理器可以二进制数据转换成图像,并显示它

using generic handler you can convert binary data into image and display it

code:
设定图像控制的网址为
Image1.ImageUrl =〜/ ShowImage.ashx ID =+身份证;

其中ShowImage.ashx是一个通用的处理程序文件。

where ShowImage.ashx is a generic handler file.

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
       Int32 empno;
       if (context.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(context.Request.QueryString["id"]);
       else
            throw new ArgumentException("No parameter specified");

       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(empno);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);

       while (byteSeq > 0)
       {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
       }      
       //context.Response.BinaryWrite(buffer);
    }

    public Stream ShowEmpImage(int empno)
    {
        string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT* FROM  table WHERE empid = @ID";
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }
}

博客文章中:保存和检索二进制数据asp.net C#图片

Blog Article : Save and retrieve image from binary data asp.net c#