Mik*_*per 6 c# bitmapimage bitmapencoder uwp
我通过URI(Web或文件系统)获取图像,并希望将其编码为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();
Run Code Online (Sandbox Code Playgroud)
问题是,这段代码挂起了await enc.FlushAsync().请帮忙!谢谢.
我不知道为什么你的代码会挂起 - 但你使用的是几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();
}
}
Run Code Online (Sandbox Code Playgroud)
(我image是一个WriteableBitmap;不确定你的raw是什么?)