Convert a BitmapImage to byte array in UWP

AymenDaoudi picture AymenDaoudi · Mar 19, 2016 · Viewed 8.9k times · Source

How can I convert a BitmapImage object to byte array in UWP ? in .Net it is easy to achieve, even in previous WinRT versions, looked all over the internet but without success, one of the solutions was to use a WriteableBitmap like mentioned in this answer, but in the current version of UWP, constructing a WriteableBitmap out of a BitmapImage isn't possible, any work around ?

Answer

fillobotto picture fillobotto · Mar 20, 2016

Since you start from image url, the only way I can figure out is to get the stream of the image. To do this, RandomAccessStreamReference.CreateFromUri() method is really useful.

Windows.Storage.Streams.IRandomAccessStream random = await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("http://...")).OpenReadAsync();

Then we have to decode the stream in order to be able to read all pixels for later usage.

Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(random);
Windows.Graphics.Imaging.PixelDataProvider pixelData = await decoder.GetPixelDataAsync();

Finally you can access pixel buffer in such a way.

byte[] bytes = pixelData.DetachPixelData();