Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a WriteableBitmap as a file?

I have a WriteableBitmap that I need to save in a file. I have a feeling I need the AsStream() extension method on WriteableBitmap.PixelBuffer. However, I don't see that extension method on my WriteableBitmap.

  1. Should AsStream() be on all WriteableBitmaps?
  2. Once I get AsStream(), what do I do next?
like image 917
royco Avatar asked Jun 17 '13 05:06

royco


1 Answers

Here you go !!!

using System.Runtime.InteropServices.WindowsRuntime;

private async Task<StorageFile> WriteableBitmapToStorageFile(WriteableBitmap WB, FileFormat fileFormat)
{
    string FileName = "MyFile.";
    Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
    switch (fileFormat)
    {
        case FileFormat.Jpeg:
            FileName += "jpeg";
            BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
            break;

        case FileFormat.Png:
            FileName += "png";
            BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
            break;

        case FileFormat.Bmp:
            FileName += "bmp";
            BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
            break;

        case FileFormat.Tiff:
            FileName += "tiff";
            BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
            break;

        case FileFormat.Gif:
            FileName += "gif";
            BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
            break;
    }

    var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.GenerateUniqueName);
    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);
        Stream pixelStream = WB.PixelBuffer.AsStream();
        byte[] pixels = new byte[pixelStream.Length];
        await pixelStream.ReadAsync(pixels, 0, pixels.Length);

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

private enum FileFormat
{
    Jpeg,
    Png,
    Bmp,
    Tiff,
    Gif
}
like image 130
Farhan Ghumra Avatar answered Oct 03 '22 15:10

Farhan Ghumra