2012-12-31 31 views
0

我正在製作一個書店網站。我使用Visual Studio 2010和MS SQL數據庫。我有關於書籍的圖像。我在數據庫中有一個Book表,並且這個表中有一個圖像列。如何將System.Drawing.Image設置爲datalist模板項目中的System.ui.WebControls.Image

我將這些圖像(以字節數組格式)保存在數據庫中。

我在Windows窗體應用程序中測試過它,一切正常。我的意思是我可以檢索圖像並保存到數據庫。當我從數據庫中檢索它們時,我將它們保存在Book類中(以System.Drawing.Image格式)。

public Book 
    { 
      private int id; 
      private System.Drawing.Image image; 
      // name and other .. informations, constructor, get and set methods; 
    } 

    public BookLayer 
    { 
      // after call this method i can get all informations from database 
      public static List<Book> getBooks() 
      { 
      } 
    } 

我在Asp.net 4 Web Project中使用datalist和objectdatasource。我爲objectdatasource編寫了Book和BookLayer類。我可以在數據列表中顯示除圖像以外的所有信息。 因爲圖像是Book類中的System.Drawing.Image,但是圖像是在datalist模板項中的System.ui.WebControls.Image。格式不同。我怎樣才能做到這一點 ?那是錯的嗎?請給我任何建議。

+0

您可以使用處理程序(.ashx)來顯示圖像 –

+1

問題已被問[之前](http://stackoverflow.com/questions/1357826/converting-system-web-ui-webcontrols-image-to-system-drawing-image)與笑rt回答說,您不能將System.Drawing.Image轉換爲WebControls.Image,因爲您嘗試將圖像資源轉換爲HTML控件。最好的做法是編寫一個加載例程來從數據庫檢索圖像信息,並在你的應用程序中使用它[這裏](http://forums.asp.net/t/1767962.aspx/1) – SaschaM78

回答

0

是使用處理程序。你可以做添加模板字段

<ItemTemplate> 
<img border="2" width="150px" src="../images/loading.gif" onload="getpic(this,'<%# Eval("bkid")%>');"/> 
</ItemTemplate> 

使用下面的Java腳本 函數方法GetPic(IMG,PID){

try { 
img.onload = null; 
img.src = '../Getimage.ashx?id=' + pid; 
} catch (e) { 
alert(e); 
} 
} 
</script> 

在getimage.ashx

byte[] imageBytes = ;// ToDOget your byte 
      Bitmap newBmp = ConvertToBitmap(imageBytes); 
      if (newBmp != null) 
      { 
       newBmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); 
       newBmp.Dispose(); 
      } 
+0

感謝你們所有人SaschaM78,我遵循你的建議,並使用本網站上描述的處理程序進行操作http://csharpdotnetfreak.blogspot.com/2009/07/display-images-gridview-from-database.html –

相關問題