2014-02-27 45 views
5

我正在開發Windows 8商店應用程序。我是新手。如何將字節數組轉換爲ImageSource for Windows 8.0商店應用程序

我以字節數組(byte [])的形式接收圖像。

我必須將其轉換回圖像並將其顯示在圖像控制中。

到目前爲止我在屏幕上有按鈕和圖像控制。當我點擊按鈕,我打電話以下功能

private async Task LoadImageAsync() 
{ 
    byte[] code = //call to third party API for byte array 
    System.IO.MemoryStream ms = new MemoryStream(code); 
    var bitmapImg = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); 

    Windows.Storage.Streams.InMemoryRandomAccessStream imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); 

    Windows.Storage.Streams.DataWriter write = new Windows.Storage.Streams.DataWriter(imras.GetOutputStreamAt(0)); 
    write.WriteBytes(code); 
    await write.StoreAsync(); 
    bitmapImg.SetSourceAsync(imras); 
    pictureBox1.Source = bitmapImg; 
} 

這不能正常工作。任何想法? 當我調試時,我可以看到ms中的字節數組。但它沒有轉換爲bitmapImg。

回答

8

我發現Codeproject

public class ByteImageConverter 
{ 
    public static ImageSource ByteToImage(byte[] imageData) 
    { 
     BitmapImage biImg = new BitmapImage(); 
     MemoryStream ms = new MemoryStream(imageData); 
     biImg.BeginInit(); 
     biImg.StreamSource = ms; 
     biImg.EndInit(); 

     ImageSource imgSrc = biImg as ImageSource; 

     return imgSrc; 
    } 
} 

這應該工作堡壘你以下。

+0

湯姆嗨!此解決方案適用於WPF。我無法在Windows Store應用程序的BitmapImage類中找到BefinInit()方法(http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.bitmapimage.aspx) – Developer

+0

任何想法!!!請任何人 – Developer

1

我在另一個線程(Image to byte[], Convert and ConvertBack)中找到了以下答案。我在Windows Phone 8.1項目中使用了這個解決方案,並不確定Windows Store應用程序,但我相信它會起作用。

public object Convert(object value, Type targetType, object parameter, string culture) 
    { 
     // Whatever byte[] you're trying to convert. 
     byte[] imageBytes = (value as FileAttachment).ContentBytes; 

     BitmapImage image = new BitmapImage(); 
     InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream(); 
     ms.AsStreamForWrite().Write(imageBytes, 0, imageBytes.Length); 
     ms.Seek(0); 

     image.SetSource(ms); 
     ImageSource src = image; 

     return src; 
    } 
2

你可以嘗試這樣的事情:

public object Convert(object value, Type targetType, object parameter, string language) 
{ 
    byte[] rawImage = value as byte[]; 

    using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) 
    { 
     using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0))) 
     { 
      writer.WriteBytes((byte[])rawImage); 

      // The GetResults here forces to wait until the operation completes 
      // (i.e., it is executed synchronously), so this call can block the UI. 
      writer.StoreAsync().GetResults(); 
     } 

     BitmapImage image = new BitmapImage(); 
     image.SetSource(ms); 
     return image; 
    } 
} 
相關問題