Showing image in GridView from the database?

2020-05-03 11:29发布

问题:

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.

回答1:

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

Code: Set image control url as Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

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

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



回答2:

the blog may give you some help http://hi.baidu.com/pxvddcbpbrbmqxq/item/3de72787e9e1c6eae496e098