What is the best way to create a byte array from an Image? I have seen many methods but in WinRT none of them worked.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答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;
}
}
}
}
回答2:
here is one way http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.writeablebitmap.aspx
alternatively if you have the Image saved on FS, just create a StorageFile and use the stream to get byte[]
回答3:
The magic is in the DataReader class. For example ...
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);
回答4:
I have used the method from Charles 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();
}