Search code examples
c#windows-runtimewindows-store-appswriteablebitmapimagesource

Convert ImageSource to WriteableBitmap in Metro Windows 8


I was wondering how I could go about converting an ImageSource object (in my case the source property of an image element) to a WriteableBitmap. The WriteableBitmap(BitmapSource) constructor doesn't work in Windows 8 Metro, so I can't do that.

I've tried to load the ImageSource object into a stream and then use WriteableBitmap.SetSource(stream), but I can't figure out how do load the image in a stream either.

InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
BitmapEncoder enc = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras);

byte[] pixelArray = new byte[(uint)photoBox.Height * (uint)photoBox.Width * 4];

enc.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight,
                 (uint)photoBox.Width, (uint)photoBox.Height, 96, 96, pixelArray);

I've also added this helper method I found online:

public Byte[] BufferFromImage(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}

The problem is that BitmapImage no longer has the StreamSource method.


Solution

  • I got an answer on the MSDN forums.

    There is no way to extract the image data from an ImageSource. You will need to keep track of the original source of the information and recreate the image in the WriteableBitmap from the original source. If you know you are going to need to do this you may be better off just using a WriteableBitmap as your ImageSource to begin with.

    Source