【问题标题】:how to show image from database in asp:image with linq?如何在asp中显示数据库中的图像:带有linq的图像?
【发布时间】:2013-06-19 03:41:09
【问题描述】:

这是我在数据库中的表:

我像这样读取数据库:

DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);

所以,thisuser.picture 是图像的句柄。但是如何在我的页面上的 asp:image 控件中显示它?

编辑 我用这段代码保存图片:

DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);
byte[] filebyte = FileUpload1.FileBytes;
System.Data.Linq.Binary fileBinary = new System.Data.Linq.Binary(filebyte);
thisuser.picture = fileBinary;
db.SubmitChanges();

有什么问题吗?

【问题讨论】:

  • 你使用什么格式的图片?此外,image 是 SQL Server 中已弃用的类型 - 您可能希望改用 varbinary
  • 通常图片格式为jpg
  • 我不得不说这是一个完美的:你试过什么?。说真的,如果你给我们看,这篇文章会受益匪浅。

标签: asp.net linq


【解决方案1】:

ASP.NET Image 控件松散地表示 HTML 中的 <img> 标记。因此,您只能通过将 URL 设置为要嵌入页面中的图像内容来将图像放入 HTML 文档中。

<img src="images/picture.png" />

这意味着您需要一种机制来接受请求图像资源的 HTTP 请求,并返回包含图像二进制数据的响应。

使用 ASP.NET Web API,这变成了一个简单的操作来实现:

public HttpResponseMessage GetImage(string username)
{
    DataClassesDataContext db = new DataClassesDataContext();
    usertable thisuser = db.usertables.FirstOrDefault(
        p => p.username == username);

    if (thisuser == null)
    {
        return new HttpResponseMessage(HttpStatusCode.NotFound)); 
    }

    // Create a stream to return to the user.
    var stream = new MemoryStream(thisuser.picture.ToArray());

    // Compose a response containing the image and return to the user.
    var result = new HttpResponseMessage();

    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
            new MediaTypeHeaderValue("image/jpeg");

    return result;
}

如果您不能使用 Web API,则必须实现 HTTP 处理程序才能完成相同的工作。

在您的 ASP.NET 页面中,您必须将属性 ImageUrl 设置为为您的控制器/处理程序配置的地址,包括作为 URL 一部分的用户名。

【讨论】:

    【解决方案2】:
    <asp:Image ImageUrl='<%# GetImage(Eval("IMG_DATA")) %>' /> 
    

    上面我们告诉 ASPX 引擎我们要获取列 [IMG_DATA] 的值,并将其传递给页面的 GetImage 方法,该方法应该返回一个有效的图像。那么,让我们在页面类中实现该方法:

    public string GetImage(object img)
    {
       return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
    }
    

    【讨论】:

    • 非常适合简单且纯粹的数据绑定解决方案:)
    【解决方案3】:

    您需要创建通用处理程序 - 我们将其命名为 ImageHandler.ashx,它将位于您的 Web 应用程序的根目录中。

    public class ImageHandler : IHttpHandler {
      public void ProcessRequest(HttpContext context) {
        // here is the tricky part - you don't store image type anywhere (you should)
        // assuming jpeg
        context.Response.ContentType = "image/jpeg";
    
        DataClassesDataContext db = new DataClassesDataContext();
        if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null) {
          var thisuser = db.usertables.First(p => p.username == HttpContext.Current.User.Identity.Name);
          if (thisuser != null) {
            byte[] buffer = thisuser.picture.ToArray();
            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
          }
        }
      }
    
      public bool IsReusable {
        get { return false; }
      }
    }
    

    然后在页面中,添加:

    <asp:Image runat="server" ImageUrl="~/ImageHandler.ashx" />
    

    几点说明:

    你应该考虑缓存图片

    你应该从 image sql 类型切换到 varbinary (http://msdn.microsoft.com/en-us/library/ms187993.aspx)

    您应该将图像 mimetype 存储在某处(如果它是 jpeg、png、bmp) - 最好在同一个表中,并在处理程序中提供正确的 mimetype

      -

    【讨论】:

      【解决方案4】:

      如果 thisuser.picture 有正确的图片路径,你可以试试这样:

      Image im = new Image();
      im.ID = "myImg";
      im.ImageUrl = thisuser.picture.toString();
      this.Controls.Add(im);
      

      我假设您正在使用网络表单(我认为这没有什么区别)。

      此外,这可能需要刷新页面。 “this”指的是 Page 对象(在我的例子中)。

      【讨论】:

      • 仔细查看表信息,它不是路径,是 blob
      【解决方案5】:

      您不能使用 ASP.NET Image 控件直接呈现它(或者至少不是我立即意识到的)。很快我的头顶:

      解决方案 1: 您的图像需要一些 HttpHandler。在您的 asp:image 标记中,您需要一个 ImageUrl,它将被这个特定的 HttpHandler 拾取。在那里,您可以使用正确的 MIME 类型和标头将数据库中的图像内容作为字节写出。

      解决方案 2: 看看在 URL 中嵌入数据,也许您可​​以像这样写出您的图像并将其添加到 asp:image ImageUrl 中:https://en.wikipedia.org/wiki/Data_URI_scheme

      【讨论】:

        【解决方案6】:

        创建 ashx 页面。在它上面使用这样的东西

        public void ProcessRequest(HttpContext context)
        {
        
             context.Response.ContentType = "image/jpeg";
             Stream strm = new MemoryStream(GetImage(ID));
             long length = strm.Length;
             byte[] buffer = new byte[length];
             int byteSeq = strm.Read(buffer, 0, 2048);
        
             while (byteSeq > 0)
             {
                   context.Response.OutputStream.Write(buffer, 0, byteSeq);
                   byteSeq = strm.Read(buffer, 0, 2048);
              }
        }
        
        1. 开启获取图片方法

          public static byte[] GetImage(string ImageId)
          {
              byte[] img = null;
          
              DataTable dt = new DataTable();
              SqlCommand cmd = new SqlCommand();
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.CommandText = "USP_SELECT_GLOBAL_METHOD";
              cmd.Parameters.AddWithValue("@EVENT", 5);
              cmd.Parameters.AddWithValue("@CODE", ImageId);
              cmd.Connection = DL_CCommon.Connection();
              SqlDataReader dr = null;
              dr = cmd.ExecuteReader();
              if (dr.Read())
              {
                  img = (byte[])dr[0];
              }
              dr.Close();
              return img;
          }
          

          这个方法返回图片作为你的ID。

        2. 在你的 aspx 页面上..

          Image1.ImageUrl = "somthing.ashx?ID="+userImageID;
          

        我希望它会起作用。正如我发现它在我自己的工作。谢谢

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-29
          • 2015-07-02
          • 2015-06-22
          • 2023-04-01
          • 2022-01-26
          • 2011-01-29
          • 1970-01-01
          相关资源
          最近更新 更多