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.
4 Answers
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;
}
}
}
}
Comments
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[]
Comments
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);
2 Comments
thumbmunkeys
i guess he meant reading the pixel data, not the file contents
Jim O'Neil
thought the same thing... BUT in order to get the pixel data you have to reload the Image (capital "I") into a WriteableBitmap, and if you're doing that why not just read the source directly as @JP mentioned!
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();
}