使用通用Windows应用程序并尝试绑定xaml中字节数组的图像。我有点失落。在xaml我有类似的东西:
<Image Source="{Binding SelectedImageSource}"
Stretch="UniformToFill"
Grid.Row="1"/>
在我的视图模型中我有
private byte[] _selectedImageSource;
public byte[] SelectedImageSource
{
get { return _selectedImageSource; }
set
{
_selectedImageSource = value;
OnPropertyChanged(nameof(SelectedImageSource));
}
}
但我在这里看不到图像。我认为我需要做的是将byte []转换为Windows.UI.Xaml.Media.Imaging.BitmapImage。虽然如何做到这一点,我并不是百分之百确定,如果这是正确的事情。
答案 0 :(得分:4)
试试这个:
public static async Task<BitmapImage> GetBitmapAsync(byte[] data)
{
var bitmapImage = new BitmapImage();
using (var stream = new InMemoryRandomAccessStream())
{
using (var writer = new DataWriter(stream))
{
writer.WriteBytes(data);
await writer.StoreAsync();
await writer.FlushAsync();
writer.DetachStream();
}
stream.Seek(0);
await bitmapImage.SetSourceAsync(stream);
}
return bitmapImage;
}
您也可以尝试更简单的版本described here,但我认为我遇到了一些问题,这就是为什么我现在使用上面的代码。
答案 1 :(得分:2)
工作正常:
public async Task<BitmapImage> MyBitmapAsync(byte[] value)
{
if (value == null || !(value is byte[]))
return null;
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])value);
writer.StoreAsync().GetResults();
}
var image = new BitmapImage();
image.SetSource(ms);
return image;
}
}
答案 2 :(得分:1)
但我还有另一种使用WriteableBitmap
的方法。您可以按URI和文件设置图像。
UWP可以转换WriteableBitmap
和byte[]
将属性更改为
private WriteableBitmap _selectedImageSource;
public WriteableBitmap SelectedImageSource
{
get { return _selectedImageSource; }
set
{
_selectedImageSource = value;
OnPropertyChanged(nameof(SelectedImageSource));
}
}
并将byte[]
设为WriteableBitmap
private async Task<ImageSource> FromBase64(byte[] bytes)
{
var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
return output;
}
如果您想从文件中读取,请使用
private static async Task<WriteableBitmap> OpenWriteableBitmapFile(StorageFile file)
{
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
WriteableBitmap image = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
image.SetSource(stream);
return image;
}
}
如果您想将WriteableBitmap
转换为byte[]
,请参阅:http://lindexi.oschina.io/lindexi/post/win10-uwp-%E8%AF%BB%E5%8F%96%E4%BF%9D%E5%AD%98WriteableBitmap-BitmapImage/
Thx https://codepaste.net/ijx28i提供代码。