我正在开发Windows 8商店应用程序。我是新人。
我正在以字节数组(byte [])的形式接收图像。
我必须将其转换回Image并在Image Control中显示它。
到目前为止,我在屏幕上有按钮和图像控件。当我点击按钮时,我调用以下功能
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。
答案 0 :(得分:8)
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;
}
}
此代码应该适合您。
答案 1 :(得分: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;
}
}
答案 2 :(得分:1)
我在另一个帖子(Image to byte[], Convert and ConvertBack)中找到了以下答案。我在Windows Phone 8.1项目中使用此解决方案,不确定Windows应用商店应用程序,但我相信它会起作用。
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;
}