繁体   English   中英

UWP将图像编码为PNG

[英]UWP encode image to PNG

我通过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();

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

我不知道为什么你的代码会挂起 - 但你正在使用几个IDisposable thingies,这可能是相关的。 无论如何,这里有一些代码可以完成您正在尝试做的事情,它确实有效:

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是什么?)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM