How to save WriteableBitmap as a file?

I have a WriteableBitmap that I need to save to a file. It seems to me that I need an AsStream() extension method on WriteableBitmap.PixelBuffer . However, I do not see this extension method on my WriteableBitmap .

  • Should AsStream() be on all WriteableBitmap s?
  • As soon as I get AsStream() , what should I do next?
+4
source share
1 answer

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 } 
+11
source

Source: https://habr.com/ru/post/1486536/


All Articles