WriteableBitmap到PNG

时间:2015-11-18 14:39:02

标签: c# windows-store-apps winrt-xaml writeablebitmap

我正在编写一个简单的WindowsStore应用程序,我无法找到如何将WriteableBitmap保存为PNG图像格式的某些内存流,以便获取此PNG图像的字节。

到目前为止我能找到的是如何在WP7.1上做到这一点,但它不起作用。

任何人都可以共享代码段或指向有用的资源吗?

更新:

我使用WriteableBitmap来绘制它。

我有这种扩展方法。

public static async Task<byte[]> ConvertToPngBytes(this WriteableBitmap bitmap)
{
   using (IRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
   {
      BitmapEncoder encode = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, memoryStream);
      byte[] buf = bitmap.PixelBuffer.ToArray();
      encode.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, buf);
      await encode.FlushAsync();
      await memoryStream.FlushAsync();

      var stream = memoryStream.AsStream();
      byte[] result = new byte[stream.Length];
      stream.Read(result, 0, result.Length);
      return result;
   }
}

它挂在await encode.FlushAsync();

2 个答案:

答案 0 :(得分:1)

事实证明,BitmapEncoder需要一个充满png数据的流。我在互联网上找到的每个示例代码都需要一个现有的PNG文件,或者用一个选择器等创建一个。我只想将我的WriteableBitmap保存为PNG格式的字节数组。

作为解决方案,我制作了一个1x1像素的PNG文件,并将其字节复制到一个字节数组中。我可以使用这个字节数组进行一些操作,而不需要从文件中写入/读取任何内容。

以下是解决方案:

static readonly byte[] PngBytes = {
    137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1,
    8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 1, 115, 82, 71, 66, 0, 174, 206, 28, 233, 0,
    0, 0, 4, 103, 65, 77, 65, 0, 0, 177, 143, 11, 252, 97, 5, 0, 0, 0, 9, 112, 72, 89, 115,
    0, 0, 14, 195, 0, 0, 14, 195, 1, 199, 111, 168, 100, 0, 0, 0, 24, 116, 69, 88, 116, 83,
    111, 102, 116, 119, 97, 114, 101, 0, 112, 97, 105, 110, 116, 46, 110, 101, 116, 32, 52,
    46, 48, 46, 51, 140, 230, 151, 80, 0, 0, 0, 13, 73, 68, 65, 84, 24, 87, 99, 248, 255, 
    255, 255, 127, 0, 9, 251, 3, 253, 5, 67, 69, 202, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66,
    96, 130
};

public static async Task<byte[]> ConvertToPngBytes(this WriteableBitmap bitmap)
{
    using (var memoryStream = new InMemoryRandomAccessStream())
    {
        await memoryStream.WriteAsync(PngBytes.AsBuffer());
        memoryStream.Seek(0);

        BitmapEncoder encode = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId,
            memoryStream);
        byte[] buffer = bitmap.PixelBuffer.ToArray();
        encode.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, 
            (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, buffer);
        await encode.FlushAsync();
        var stream = memoryStream.AsStream();
        stream.Seek(0, SeekOrigin.Begin);
        byte[] result = new byte[stream.Length];
        stream.Read(result, 0, result.Length);
        return result;
    }
}

答案 1 :(得分:0)

我做类似的事情

                    StorageFile photoFile = await StorageFile.GetFileFromPathAsync(Windows.ApplicationModel.Package.Current.InstalledLocation.Path + @"\Images\CurrentFace.jpg");
                    using (IRandomAccessStream fileStream = await photoFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encode = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream); //Here try PNG
                        byte[] buf = displaySource.PixelBuffer.ToArray();
                        encode.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)displaySource.PixelWidth
                        , (uint)displaySource.PixelHeight, 96.0, 96.0, buf);
                        await encode.FlushAsync();
                        await fileStream.FlushAsync();
                    }

我没有使用过writablebitmap所以我的答案是不完整的,但是从文件而不是从writablebitmap加载流要容易得多。我曾经做过像writablebitmap.pixelbuffer.asstream()这样的事情,但这不起作用,因为流将缺少不在pixelbuffer中的关键信息

此处还有我保存到文件的代码。注意:必须存在一个已存在的文件才能保存,因此您只需将一个空白.png放入目录中,然后将实际图像保存到该目录中即可。您可以将writableBitmap存储在Framework元素中,然后调用此函数。

    async Task<RenderTargetBitmap> SaveToFileAsync(FrameworkElement uielement, StorageFile file)
    {
        if (file != null)
        {
            CachedFileManager.DeferUpdates(file);

            Guid encoderId = GetBitmapEncoder(file.FileType);

            try
            {
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    return await CaptureToStreamAsync(uielement, stream, encoderId);
                }
            }
            catch (Exception ex)
            {
                //DisplayMessage(ex.Message);
            }

            var status = await CachedFileManager.CompleteUpdatesAsync(file);
        }

        return null;
    }

        async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId)
    {
        try
        {
            var renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(uielement);

            var pixels = await renderTargetBitmap.GetPixelsAsync();

            var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
            var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);
            encoder.SetPixelData(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Ignore,
                (uint)renderTargetBitmap.PixelWidth,
                (uint)renderTargetBitmap.PixelHeight,
                logicalDpi,
                logicalDpi,
                pixels.ToArray());

            await encoder.FlushAsync();

            return renderTargetBitmap;
        }
        catch (Exception ex)
        {
            //DisplayMessage(ex.Message);
        }

        return null;
    }

您的更新代码无法正常工作,因为必须将BitmapEncoder分配给包含图片数据的流。当你使用await BitmapEncoder.CreateAsync()时,你使用没有数据的memoryStream(它刚刚被初始化)。