UWP将图像编码为PNG

时间:2016-05-24 07:37:02

标签: c# uwp bitmapimage bitmapencoder

我通过URI(网络或文件系统)获取图像,并希望将其编码为PNG并保存到临时文件中:

var bin = new MemoryStream(raw).AsRandomAccessStream();  //raw is byte[]
var dec = await BitmapDecoder.CreateAsync(bin);
var pix = (await dec.GetPixelDataAsync()).DetachPixelData();

var res = new FileStream(Path.Combine(ApplicationData.Current.LocalFolder.Path, "tmp.png"), FileMode.Create);
var enc = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, res.AsRandomAccessStream());
enc.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, dec.PixelWidth, dec.PixelHeight, 96, 96, pix);
await enc.FlushAsync();  //hangs here
res.Dispose();

问题是,此代码挂起await enc.FlushAsync()行。 请帮忙!感谢。

1 个答案:

答案 0 :(得分:6)

我不确定您的代码为何会挂起 - 但您使用的是几个IDisposable内容,可能相关。无论如何,这里有一些代码可以完成您正在尝试的任务,并且确实有效:

StorageFile file = await ApplicationData.Current.TemporaryFolder
    .CreateFileAsync("image", CreationCollisionOption.GenerateUniqueName);
using (IRandomAccessStream outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    using (MemoryStream imageStream = new MemoryStream())
    {
        using (Stream pixelBufferStream = image.PixelBuffer.AsStream())
        {
            pixelBufferStream.CopyTo(imageStream);
        }

        BitmapEncoder encoder = await BitmapEncoder
            .CreateAsync(BitmapEncoder.PngEncoderId, outputStream);
        encoder.SetPixelData(
            BitmapPixelFormat.Bgra8,
            BitmapAlphaMode.Ignore,
            (uint)image.PixelWidth,
            (uint)image.PixelHeight,
            dpiX: 96,
            dpiY: 96,
            pixels: imageStream.ToArray());
        await encoder.FlushAsync();
    }
}

(我的imageWriteableBitmap;不确定您的raw是什么?)