2012-05-14 109 views
2

我有兩個功能:如何將「爲System.Drawing.Image」添加到「System.Web.UI.WebControls.Image」

功能1:ImageToByteArray:是用來將圖像轉換成一個字節然後將數組存儲在Oracle數據庫的BLOB字段中。

  public byte[] ImageToByteArray(string sPath) 
      { 
       byte[] data = null; 
       FileInfo fInfo = new FileInfo(sPath); 
       long numBytes = fInfo.Length; 
       FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read); 
       BinaryReader br = new BinaryReader(fStream); 
       data = br.ReadBytes((int)numBytes); 
       return data; 
      } 

功能2:ByteArrayToImage:用於轉換從數據庫中的字節數組成圖像:

  public System.Drawing.Image ByteArrayToImage(byte[] byteArray) 
      { 
       MemoryStream img = new MemoryStream(byteArray); 
       System.Drawing.Image returnImage = System.Drawing.Image.FromStream(img); 
       return returnImage; 
      } 

以我標記我有一個Imgage控制: <asp:Image ID="Image1" runat="server" />

在後面的代碼我想將函數2的返回值(類型爲System.Drawing.Image)指定給類型爲「(image)」的控件(System.Web。 UI.WebControls.Image)。

很明顯,我不能只分配: image1 = ByteArrayToImage(byteArray); ,因爲我得到了以下錯誤:無法隱式轉換類型「爲System.Drawing.Image」到「System.Web.UI.WebControls.Image」

有沒有辦法做到這一點?

回答

3

你不能。 WebControls.Image只是一個圖像url的HTML容器 - 你不能直接在其中存儲圖像數據,只需將引用(url)存儲到一個圖像文件。

如果您需要動態檢索圖像數據,通常的方法是創建一個圖像處理程序來處理請求並將圖像作爲瀏覽器可以顯示的流返回。

看到這個question

1

看起來你只是想要一個簡單的方法,以圖像的字節數組轉換成圖片。沒問題。我發現一個article,幫助了我很多。

System.Web.UI.WebControls.Image image = (System.Web.UI.WebControls.Image)e.Item.FindControl("image"); 

    if (!String.IsNullOrEmpty(currentAd.PictureFileName)) 
    { 
     image.ImageUrl = GetImage(currentAd.PictureFileContents); 
    } 
    else 
    { 
     image.Visible = false; 
    } 

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

PictureFileContents是一個Byte [],這就是函數GetImage作爲一個對象所取的。

+0

+1對於「data:image/jpg; base64」,+ Convert.ToBase64String((byte [])img); – Amol

0

我認爲這是可能的,我希望它有幫助。我的解決方案是:

public System.Web.UI.WebControls.Image HexStringToWebControlImage(string hexString) 
{ 
    var imageAsString = HexString2Bytes(hexString); 

    MemoryStream ms = new MemoryStream(); 
    ms.Write(imageAsString, 0, imageAsString.Length); 

    if (imageAsString.Length > 0) 
    { 
     var base64Data = Convert.ToBase64String(ms.ToArray()); 
     return new System.Web.UI.WebControls.Image 
     { 
      ImageUrl = "data:image/jpg;base64," + base64Data 
     }; 
    } 
    else 
    { 
     return null; 
    } 
} 

public byte[] HexString2Bytes(string hexString) 
{ 
    int bytesCount = (hexString.Length)/2; 
    byte[] bytes = new byte[bytesCount]; 
    for (int x = 0; x < bytesCount; ++x) 
    { 
     bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16); 
    } 

    return bytes; 
} 
相關問題