1

For my application, I am trying to convert an WriteableBitmap to byte[] to store in the database, and then from byte[] to BitmapImage to display back to the user.

My current methods that so far, produce no results:

public byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
{
    using (Stream stream = bitmap.PixelBuffer.AsStream())
    using (MemoryStream memoryStream = new MemoryStream())
    {
        stream.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}

To convert from byte array to BitmapImage, I use:

using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{

    using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
    {
        writer.WriteBytes((byte[])buffer);
        writer.StoreAsync().GetResults();
    }


    var image = new BitmapImage();
    image.SetSource(ms);
    imageByteTest.Source = image;
}            

There is good documentation for Silverlight applications I have found, but very little in the way for Windows Store Universal Runtime Applications. Where are these methods going wrong?

Bart
  • 9,925
  • 7
  • 47
  • 64

2 Answers2

0

You might want to take a look at the WriteableBitmapEx library which contains some extensions to WriteableBitmap, as well as some core features like your conversion of WriteableBitmap to byte array and vice versa.

James Croft
  • 1,680
  • 13
  • 25
0

I wrote a converter for ByteArrayToBitmapImage:

 public object Convert(object value, Type targetType, object parameter, string language)
    {
        var byteArray = value as byte[];
        var bitmapImage = new BitmapImage();
        Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                using (var stream = new MemoryStream(byteArray))
                {
                    bitmapImage.SetSourceAsync(stream.AsRandomAccessStream());
                }
            });

        return bitmapImage;

    }

And byte[] -> WriteableBitmap

  public static WriteableBitmap PrepareWritableBitmap(Size size, byte[] pixels)
    {
        uint height = (uint)Math.Floor(size.Height);
        uint width = (uint)Math.Floor(size.Width);

        WriteableBitmap bmp = new WriteableBitmap((int)width, (int)height);
        Stream pixStream = bmp.PixelBuffer.AsStream();
        pixStream.Write(pixels, 0, (int)(width * height * 4));
        //4 is a channel number for RGBA, for RGB is 3 channels
        return bmp;
    }