How to save a WriteableBitmap as a file?
10,021
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
}
Related videos on Youtube
Author by
royco
Updated on September 15, 2022Comments
-
royco over 1 year
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 myWriteableBitmap
.- Should
AsStream()
be on allWriteableBitmap
s? - Once I get
AsStream()
, what do I do next?
- Should
-
royco almost 11 yearsAt
WB.PixelBuffer.AsStream()
, I get: 'Windows.Storage.Streams.IBuffer' does not contain a definition for 'AsStream' and the best extension method overload 'System.IO.WindowsRuntimeStreamExtensions.AsStream(Windows.Storage.Streams.IRandomAccessStream)' has some invalid arguments -
Farhan Ghumra almost 11 yearsYou need to add
using System.Runtime.InteropServices.WindowsRuntime;
-
gayan1991 almost 8 yearsWhy image is not saved as transparent image?
-
dude over 7 yearshi there @Xyroid , if we use that, are we supposed to respect the file format? To be specific, let's say that I create a WriteableBitmap from a PNG file, then I encode it to JPEG.. is it a good idea?