6

I want to convert a WriteableBitmap image to a Byte[] array using C# code in Windows store metro style apps.

DIF
  • 2,470
  • 6
  • 35
  • 49
sooraj P R
  • 259
  • 2
  • 6

1 Answers1

8

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();
        }
    }
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
  • 'IBuffer' does not contain a definition for 'AsStream' and the best extension method overload 'WindowsRuntimeStreamExtensions.AsStream(IRandomAccessStream)' requires a receiver of type 'IRandomAccessStream' – v.g. Jul 29 '15 at 14:34
  • @V.G. Since it's an extension method, you'll need to add `using System.Runtime.InteropServices.WindowsRuntime` – SepehrM Aug 13 '15 at 11:49
  • 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! – Robert J. Good Feb 10 '16 at 18:31