我通过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()
行。
请帮忙!感谢。
答案 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();
}
}
(我的image
是WriteableBitmap
;不确定您的raw
是什么?)