【问题标题】:Showing image in GridView from the database?在数据库中的 GridView 中显示图像?
【发布时间】:2012-11-06 02:39:11
【问题描述】:

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

【问题讨论】:

标签: asp.net gridview


【解决方案1】:

【讨论】:

    【解决方案2】:

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

    代码: 将图像控制 url 设置为 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();
            }
        }
    }
    

    【讨论】:

    • 它会直接从处理程序中获取图像吗?
    • @eraj:是的,这适用于我的情况。好吧,请尝试一次,如果您发现任何问题,请告诉我?
    猜你喜欢
    • 2012-05-27
    • 2023-04-11
    • 2012-11-25
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多