0

I'm writing a simple WindowsStore app and I can not find out how can I save a WriteableBitmap to some memory stream in PNG image format in order to get the bytes of this PNG image.

What I can find so far is how to do that on WP7.1 but it doesn't work.

Can anyone share a snippet or point to useful resources?

UPDATE:

I use WriteableBitmap to draw on it.

I have this extension method.

public static async Task<byte[]> ConvertToPngBytes(this WriteableBitmap bitmap)
{
   using (IRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
   {
      BitmapEncoder encode = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, memoryStream);
      byte[] buf = bitmap.PixelBuffer.ToArray();
      encode.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, buf);
      await encode.FlushAsync();
      await memoryStream.FlushAsync();

      var stream = memoryStream.AsStream();
      byte[] result = new byte[stream.Length];
      stream.Read(result, 0, result.Length);
      return result;
   }
}

It hangs on await encode.FlushAsync();

zavolokas
  • 697
  • 1
  • 5
  • 20

2 Answers2

1

It turned out that the BitmapEncoder expects a stream filled with a png data. Every example code I've got and found on the internet, requires either an existing PNG file or to creates one with a picker etc. And I simply want to save my WriteableBitmap to a byte array in PNG format.

As a solution, I've made a 1x1 pixel PNG file and copied its bytes to a byte array. Than I can do some manipulations with this byte array and don't need to write/read anything from files.

Here is the solution:

static readonly byte[] PngBytes = {
    137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1,
    8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 1, 115, 82, 71, 66, 0, 174, 206, 28, 233, 0,
    0, 0, 4, 103, 65, 77, 65, 0, 0, 177, 143, 11, 252, 97, 5, 0, 0, 0, 9, 112, 72, 89, 115,
    0, 0, 14, 195, 0, 0, 14, 195, 1, 199, 111, 168, 100, 0, 0, 0, 24, 116, 69, 88, 116, 83,
    111, 102, 116, 119, 97, 114, 101, 0, 112, 97, 105, 110, 116, 46, 110, 101, 116, 32, 52,
    46, 48, 46, 51, 140, 230, 151, 80, 0, 0, 0, 13, 73, 68, 65, 84, 24, 87, 99, 248, 255, 
    255, 255, 127, 0, 9, 251, 3, 253, 5, 67, 69, 202, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66,
    96, 130
};

public static async Task<byte[]> ConvertToPngBytes(this WriteableBitmap bitmap)
{
    using (var memoryStream = new InMemoryRandomAccessStream())
    {
        await memoryStream.WriteAsync(PngBytes.AsBuffer());
        memoryStream.Seek(0);

        BitmapEncoder encode = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId,
            memoryStream);
        byte[] buffer = bitmap.PixelBuffer.ToArray();
        encode.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, 
            (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, buffer);
        await encode.FlushAsync();
        var stream = memoryStream.AsStream();
        stream.Seek(0, SeekOrigin.Begin);
        byte[] result = new byte[stream.Length];
        stream.Read(result, 0, result.Length);
        return result;
    }
}
zavolokas
  • 697
  • 1
  • 5
  • 20
0

I do something similar like this

                    StorageFile photoFile = await StorageFile.GetFileFromPathAsync(Windows.ApplicationModel.Package.Current.InstalledLocation.Path + @"\Images\CurrentFace.jpg");
                    using (IRandomAccessStream fileStream = await photoFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encode = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream); //Here try PNG
                        byte[] buf = displaySource.PixelBuffer.ToArray();
                        encode.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)displaySource.PixelWidth
                        , (uint)displaySource.PixelHeight, 96.0, 96.0, buf);
                        await encode.FlushAsync();
                        await fileStream.FlushAsync();
                    }

I haven't used writablebitmap so my answer is incomplete, but it is much easier to load a stream from a file instead of from a writablebitmap. I once did something like writablebitmap.pixelbuffer.asstream() but this doesn't work because the stream would be missing critical info that isn't in the pixelbuffer

Also here is my code to save to a file. Note: there must be a file that already exists to save to, so you could just put a blank .png in a directory and then save your real image to it. You can store your writableBitmap in a Framework element and then call this function.

    async Task<RenderTargetBitmap> SaveToFileAsync(FrameworkElement uielement, StorageFile file)
    {
        if (file != null)
        {
            CachedFileManager.DeferUpdates(file);

            Guid encoderId = GetBitmapEncoder(file.FileType);

            try
            {
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    return await CaptureToStreamAsync(uielement, stream, encoderId);
                }
            }
            catch (Exception ex)
            {
                //DisplayMessage(ex.Message);
            }

            var status = await CachedFileManager.CompleteUpdatesAsync(file);
        }

        return null;
    }

        async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId)
    {
        try
        {
            var renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(uielement);

            var pixels = await renderTargetBitmap.GetPixelsAsync();

            var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
            var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
            encoder.SetPixelData(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Ignore,
                (uint)renderTargetBitmap.PixelWidth,
                (uint)renderTargetBitmap.PixelHeight,
                logicalDpi,
                logicalDpi,
                pixels.ToArray());

            await encoder.FlushAsync();

            return renderTargetBitmap;
        }
        catch (Exception ex)
        {
            //DisplayMessage(ex.Message);
        }

        return null;
    }

Your updated code is not working because the BitmapEncoder must be assigned to a stream with picture data. When you use await BitmapEncoder.CreateAsync() you use memoryStream which has no data (it was just initialized).

Seth Kitchen
  • 1,526
  • 19
  • 53