簡體   English   中英

從字節數組創建BitmapImage

[英]Creating BitmapImage from a byte array

我正在嘗試從服務返回的字節數組創建BitmapImage

我的代碼是:

using (sc = new ServiceClient())
{
    using (MemoryStream ms = new MemoryStream(sc.GetImage()))
    {
        Display = new BitmapImage();
        Display.BeginInit();
        Display.StreamSource = ms;
        Display.EndInit();
    }
}

但是, EndInit方法會引發異常。 它說Object reference not set to an instance of an object.

看來,Uri為空,這會導致問題。 不幸的是,我自己找不到解決方案。

好吧,事實證明,WPF綁定引起了錯誤。

private BitmapImage _display;
public BitmapImage Display
{
    get { return _display; }
    set
    {
        _display = value;
        RaisePropertyChanged("Display");
    }
}

我通過使圖像不在屬性Display本身中,而是在文件名_display中解決了該問題。 因此,以下工作正常。

using (sc = new ServiceClient())
{
    using (MemoryStream ms = new MemoryStream(sc.GetImage()))
    {
        _display = new BitmapImage();
        _display.BeginInit();
        _display.CacheOption = BitmapCacheOption.OnLoad;
        _display.StreamSource = ms;
        _display.EndInit();
    }
}

Display = _display;

u正在將memory stream直接分配給bitmap source ,這會導致error 首先,您需要獲取bytes array ,然后convert其轉換為memory stream ,然后分配給bitmap source ,僅此而已!!!

using (sc = new ServiceClient())
    {
            Byte[] array = sc.GetImage();

            Display = new BitmapImage();
            Display.BeginInit();
            Display.StreamSource = new MemoryStream(array);
            Display.EndInit();
     }

暫無
暫無

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

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