如何将WriteableBitmap保存为文件

本文关键字:文件 保存 WriteableBitmap | 更新日期: 2023-09-27 18:18:35

我有一个WriteableBitmap,我需要保存在一个文件中。我有一种感觉,我需要WriteableBitmap.PixelBuffer上的AsStream()扩展方法。但是,我没有在我的WriteableBitmap上看到这个扩展方法。

  1. AsStream()应该在所有WriteableBitmap s上吗?
  2. 一旦我得到AsStream(),我下一步该做什么?

如何将WriteableBitmap保存为文件

给你!!

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
}