从asp.net中的数据库中检索图像

时间:2013-02-18 11:27:16

标签: c# asp.net sql-server httphandler

如何使用c#从asp.net的sql数据库中检索图像。

我想从数据库中检索图像文件,然后在标签中显示图像。

我尝试使用此代码,但它无效

ASPX

 <asp:Image ID="Image1" runat="server" ImageUrl="" Height="150px" Width="165px" />

代码

 Byte[] bytes = (Byte[])ds.Tables[0].Rows[0]["image"];
 Response.Buffer = true;
 Response.Charset = "";
 Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Response.ContentType = "image/jpg";
 Response.BinaryWrite(bytes);
 Response.Flush();
 Response.End();

如何提供此图像ImageUrl=""的链接???

3 个答案:

答案 0 :(得分:15)

按如下方式创建generic http handler

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["EmployeeConnString"].ConnectionString;
         SqlConnection connection = new SqlConnection(conn);
         string sql = "SELECT empimg FROM EmpDetails 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();
       }
    }

    public bool IsReusable
    {
        get
        {
             return false;
        }
    }


}

并显示图像如下

 Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

下面有一些链接 Showing image in GridView from the database?
How to show a image in database in the image control of Asp.net?
Display image from database in ASP.net with C#
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129

答案 1 :(得分:3)

我不认为这是正确的做法。 你不应该将图像嵌入到html中,这无论如何都不是正确的方法。

我建议添加一个ashx(通用处理程序)并使用它从查询字符串生成图像,然后在页面中使用类似

的内容
<asp:Image ImageUrl='GetImage.ashx?id=12345' ... />

答案 2 :(得分:0)

With Entity Frame work

With SQL (Code Project)

<asp:Image ID="ImgProfilePic" runat="server"  />

    byte[] imagem = (byte[])(dr["IMG"]);
string PROFILE_PIC = Convert.ToBase64String(imagem);
ImgProfilePic.ImageUrl = String.Format("data:image/jpg;base64,{0}", PROFILE_PIC);