2009-06-17 106 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中顯示的圖像。

相關問題