6

我通过 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()。请帮忙!谢谢。

4

1 回答 1

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();
    }
}

(我image是一个WriteableBitmap;不确定你raw是什么?)

于 2016-05-24T10:55:51.490 回答