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

时间:2012-11-17 16:23:03

标签: asp.net gridview

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

2 个答案:

答案 0 :(得分:2)

使用通用处理程序,您可以将二进制数据转换为图像并显示它

<强>代码: 将图像控制网址设置为 Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

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

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

博客文章:Save and retrieve image from binary data asp.net c#

答案 1 :(得分:0)

相关问题