什么是创建从图像的字节数组的最佳方式? 我见过很多的方法,但在WinRT中没有一次成功。
Answer 1:
static class ByteArrayConverter
{
public static async Task<byte[]> ToByteArrayAsync(StorageFile file)
{
using (IRandomAccessStream stream = await file.OpenReadAsync())
{
using (DataReader reader = new DataReader(stream.GetInputStreamAt(0)))
{
await reader.LoadAsync((uint)stream.Size);
byte[] Bytes = new byte[stream.Size];
reader.ReadBytes(Bytes);
return Bytes;
}
}
}
}
Answer 2:
这里是一个办法http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.writeablebitmap.aspx
或者,如果你的图片保存在FS,只需创建一个StorageFile并使用流得到的byte []
Answer 3:
神奇的是在DataReader的类 。 例如 ...
var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Logo.png"));
var buf = await FileIO.ReadBufferAsync(file);
var bytes = new byte[buf.Length];
var dr = DataReader.FromBuffer(buf);
dr.ReadBytes(bytes);
Answer 4:
我用的方法从查尔斯Petzold的 :
byte[] srcPixels;
Uri uri = new Uri("http://www.skrenta.com/images/stackoverflow.jpg");
RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri);
using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
BitmapFrame frame = await decoder.GetFrameAsync(0);
PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();
srcPixels = pixelProvider.DetachPixelData();
}
文章来源: Creating a Byte array from an Image