簡體   English   中英

將字節數組轉換為bitmapimage

[英]convert array of bytes to bitmapimage

我將把字節數組轉換為System.Windows.Media.Imaging.BitmapImage並在圖像控件中顯示BitmapImage

當我使用第一個代碼時,注意到了! 沒有錯誤,也沒有顯示圖像。 但是當我使用第二個時,它工作正常! 任何人都可以說發生了什么事嗎?

第一個代碼在這里:

public BitmapImage ToImage(byte[] array)
{
   using (System.IO.MemoryStream ms = new System.IO.MemoryStream(array))
   {
       BitmapImage image = new BitmapImage();
       image.BeginInit();
       image.StreamSource = ms;
       image.EndInit();
       return image;
   }
}

第二個代碼在這里:

public BitmapImage ToImage(byte[] array)
{
   BitmapImage image = new BitmapImage();
   image.BeginInit();
   image.StreamSource = new System.IO.MemoryStream(array);
   image.EndInit();
   return image;
 }

在第一個代碼示例中,在實際加載圖像之前關閉流(通過離開using塊)。 您還必須設置BitmapCacheOptions.OnLoad以實現圖像立即加載,否則流需要保持打開,如第二個示例中所示。

public BitmapImage ToImage(byte[] array)
{
    using (var ms = new System.IO.MemoryStream(array))
    {
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad; // here
        image.StreamSource = ms;
        image.EndInit();
        return image;
    }
}

BitmapImage.StreamSource中的Remarks部分:

如果要在創建BitmapImage后關閉流,請將CacheOption屬性設置為BitmapCacheOption.OnLoad。


除此之外,您還可以使用內置類型轉換從類型byte[]轉換為ImageSource類型(或派生的BitmapSource ):

var bitmap = (BitmapSource)new ImageSourceConverter().ConvertFrom(array);

將ImageSource類型的屬性(例如Image控件的Source屬性)綁定到stringUribyte[]類型的source屬性時,將隱式調用ImageSource

在第一種情況下,您在一個using塊中定義了MemoryStream ,這會導致在您離開塊時處理該對象。 因此,您返回帶有BitmapImage (和不存在的)流的BitmapImage

MemoryStream不保留非托管資源,因此您可以保留內存並讓GC處理釋放過程(但這不是一個好習慣)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM