API to save WriteableBitmap to PNG is one of the top UserVoice requests for Universal Windows Platform. While such API does not exist in the same way as WriteableBitmap SaveJpeg() extension method, there are two workarounds.

If you are allowed (or willing) to use a third-party library, WriteableBitmapEx provides ability to save bitmap as PNG.

In case you’d like to stay free of external libraries, you can use the following solution, based on the UWP APIs:

WriteableBitmap bitmap = new WriteableBitmap(50, 50);
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(
                                 new Uri("ms-appx:///Assets/MyBitmap.jpg"));

using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
    await bitmap.SetSourceAsync(fileStream);
}

FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("PNG File", new List { ".png" });
StorageFile destFile = await picker.PickSaveFileAsync();

using (IRandomAccessStream stream = await destFile.OpenAsync(FileAccessMode.ReadWrite))
{
    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
    Stream pixelStream = bitmap.PixelBuffer.AsStream();
    byte[] pixels = new byte[pixelStream.Length];
    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                (uint) bitmap.PixelWidth, (uint) bitmap.PixelHeight, 96.0, 96.0, pixels);
    await encoder.FlushAsync();
}

This code creates WritebaleBitmap from a JPG image loaded from the assets. Than it requests a name for the converted file and uses BitmapEncoder to convert bitmap to PNG and save it.

blog comments powered by Disqus