gpt4 book ai didi

c# - UWP 将图像编码为 PNG

转载 作者:太空狗 更新时间:2023-10-29 21:32:41 24 4
gpt4 key购买 nike

我通过 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 东西,它们可能是相关的。无论如何,这里有一些代码几乎可以完成您想要做的事情,而且它确实有效:

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

关于c# - UWP 将图像编码为 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37407179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com