【问题标题】:How to retrieve an Image from MS SQL Server to bind in Gridview ASP.NET by using LINQ to SQL?如何使用 LINQ to SQL 从 MS SQL Server 检索图像以在 Gridview ASP.NET 中绑定?
【发布时间】:2010-11-03 13:59:49
【问题描述】:

我有一个二进制文件,它存储在 customerPicture 列中,该列在 CUSTOMERs 表中具有 Image 作为数据类型。

我在 LINQ to SQL 中使用这行代码保存了一张图片。

Dim db = new MyCompanyDataContext
Dim newCus = new CUSTOMERs
Dim filebyte As Byte() = fileUploader.FileBytes
Dim fileBinary As New System.Data.Linq.Binary(filebyte)
newCus.customerPicture = fileBinary

然后现在我想通过使用 LINQ to SQL 检索这个二进制文件以绑定到 ASP.NET 的 gridview 中,但我不知道如何。你能告诉我一些解决问题的方法吗?

【问题讨论】:

    标签: asp.net sql-server linq-to-sql image


    【解决方案1】:

    您可以使用 Httphandler 从数据库中检索图像。

                <ItemTemplate>
                    <asp:Image ID="imgPhoto" runat="server"/>
                </ItemTemplate>
    

    如果您在数据网格中有一个 Image 作为 ItemTemplate。

    在数据网格的 ItemDataBound 事件中,调用“HttpHandler”来显示图像。在下面的代码中,我找到了图像控件并将 imageUrl 作为 HttpHandler 文件路径。我还将 id 作为查询字符串传递给HttpHandlerFile。

            System.Web.UI.WebControls.Image photoImage = (System.Web.UI.WebControls.Image)e.Item.FindControl("imgPhoto");
            photoImage.ImageUrl = "ImageHandler.ashx?PhotoID=" + id.ToString();
    

    并在 HttpHandler 文件中使用 Linq 检索图像并显示它。

    public void ProcessRequest (HttpContext context)
    {
    context.Response.ContentType = "image/jpeg";

        int photoId = -1;
        //Check the query string.
        if (context.Request.QueryString["PhotoId"] != null && context.Request.QueryString["PhotoId"] != "")
        {
            photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
        }
    
        if (photoId != -1)
        {
            MovieDataContext db = new MovieDataContext();
            //Get the movie record based on the ID
            MovieTable movie = db.MovieTables.First(m => m.ID == photoId);
    
            System.Data.Linq.Binary fileBinary = movie.Photo;
            byte[] fileByte = fileBinary.ToArray();
            //displays the Image.
            context.Response.BinaryWrite(fileByte);
        }
    }
    

    由于这个 HttpHandler 文件映射到 datagrid 中的 imageURL,您可以看到 datagrid 中显示的图像。

    【讨论】:

      【解决方案2】:

      试试这个:

      dim ms as new MemoryStream
      ms.Write(fileBinary.ToArray(),0,fileBinary.Length)
      
      dim img as Image
      img = Image.FromStream(ms)
      
      newCus.customerPicture = img 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-06
        • 2012-03-03
        • 1970-01-01
        • 2011-04-17
        • 2010-10-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多