且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-24 08:58:17

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

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#