2009-06-17 92 views
1

我有一个二进制文件,它存储在customerPicture列中的CUSTOMERs表中具有Image作为数据类型。如何从MS SQL Server中检索图像以使用LINQ to SQL在Gridview ASP.NET中进行绑定?

我通过在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控件绑定这个二进制文件,但我不知道怎么办。你能告诉我一些方法来达到解决方案吗?

回答

0

试试这个:

dim ms as new MemoryStream 
ms.Write(fileBinary.ToArray(),0,fileBinary.Length) 

dim img as Image 
img = Image.FromStream(ms) 

newCus.customerPicture = img 
2

可以使用的HttpHandler从数据库retrive图像。

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

如果您有一个图像作为DataGrid中的ItemTemplate。

在DataGrid的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中显示的图像。

相关问题