如何将字节数组转换为ImageSource for Windows 8.0商店应用程序

我正在开发Windows 8商店应用程序。 我是新的。

我正以字节数组(byte [])的forms接收图像。

我必须将其转换回Image并将其显示在Image Control中。

到目前为止,我在屏幕上有button和图像控制。 当我点击button,我打电话以下function

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; } 

这工作不正常。 任何想法? 当我debugging时,我可以看到ms中的字节数组。 但它没有被转换成bitmapImg。

Solutions Collecting From Web of "如何将字节数组转换为ImageSource for Windows 8.0商店应用程序"

我在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; } } 

这应该适合你。

你可以尝试这样的事情:

 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 // (ie, it is executed synchronously), so this call can block the UI. writer.StoreAsync().GetResults(); } BitmapImage image = new BitmapImage(); image.SetSource(ms); return image; } } 

我在另一个线程( 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; }