I want to convert a WriteableBitmap image to a Byte[] array using C# code in Windows store metro style apps.
1 Answer
WriteableBitmap exposes PixelBuffer property of type IBuffer - a Windows Runtime interface which can be converted to a byte array with .NET Streams
byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
{
using (Stream stream = bitmap.PixelBuffer.AsStream())
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
3 Comments
v.g.
'IBuffer' does not contain a definition for 'AsStream' and the best extension method overload 'WindowsRuntimeStreamExtensions.AsStream(IRandomAccessStream)' requires a receiver of type 'IRandomAccessStream'
SepehrM
@V.G. Since it's an extension method, you'll need to add
using System.Runtime.InteropServices.WindowsRuntimeRobert J. Good
This is the only answer (after extensive searching) that works in Windows Universal projects. .Net classes and namespaces have shifted since WPF, to Win 8 metro store to Universal Windows...so this answer is gold!