0

我試圖用一個字節數組作爲源創建一個圖像對象。我究竟做錯了什麼?我試圖用字節數組作爲源創建圖像對象。我究竟做錯了什麼?

當我嘗試用字節數組作爲源數據初始化圖像對象時,會引發異常。下面是我的代碼中顯示的異常。

public class MyClass 
{ 
    publuc System.Windows.Media.Imaging.BitmapImage InstanceImage { get; set; } 

    public void GetImage() 
    { 
     // Retrieves a list of custom "Item" objects that contain byte arrays. 
     // ScvClnt is our service client. The PollQueue method is designed to return information to us. 
     lstQueue = SvcClnt.PollQueue(1); 

     // This condition always evaluates as True, since we requested exactly 1 "Item" from the service client. 
     if (lstQueue.Count == 1) 
     { 
      // lstQueue[0].InstanceImage is a byte array containing the data from an image file. 
      // I have confirmed that it is a valid TIFF image file, by writing it to disk and opening it in MSPaint. 
      if (lstQueue[0].InstanceImage != null) 
      { 
       // This condition is also True, since the image is just under 3KB. 
       if (lstQueue[0].InstanceImage.Length > 0) 
       { 
        this.InstanceImage = new System.Windows.Media.Imaging.BitmapImage(); 
        this.InstanceImage.BeginInit(); 
        this.InstanceImage.StreamSource = new System.IO.MemoryStream(lstQueue[0].InstanceImage); 
        InstanceImage.EndInit(); 
        // The call to EndInit throws a NullReferenceException. 
        // {"Object reference not set to an instance of an object."} 
        // I have confirmed that this.InstanceImage and this.InstanceImage.StreamSource are not null at this point. 
        // They are successfully assigned in the lines of code above. 
       } else InstanceImage = null; 
      } else InstanceImage = null; 
     } else InstanceImage = null; 
    } 
} 

我不知道地球上可能會出現什麼問題。
任何意見將不勝感激。

回答

2

This MSDN forum post使用這個例子作爲解決方案。

using (MemoryStream stream = new MemoryStream(abyteArray0)) 
{ 
    image.Source = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); 
} 

//The field image should be of type System.Windows.Controls.Image. 

我用BitmapFrame.Create方法,它採用僅在流作爲參數,和它的工作就像一個魅力。

3

我不知道我下面的你想要什麼你的第一眼類的事情,但是,解決原來的問題,給這一個鏡頭:

public static Image ConvertByteArrayToImage(byte[] byteArrayIn) 
    { 
     MemoryStream ms = new MemoryStream(byteArrayIn); 
     Image returnImage = Image.FromStream(ms); 
     return returnImage; 
    } 
+0

有趣的....勒米給這一槍。 – Giffyguy 2009-07-27 21:37:15

相關問題