gpt4 book ai didi

c# - 另存为 8 位 PNG

转载 作者:太空宇宙 更新时间:2023-11-03 13:14:28 24 4
gpt4 key购买 nike

我正在创建将用作数据 URI 的特定大小的占位符图像

Bitmap bitmap = new Bitmap(16, 10);

我做了一些研究,但找不到将此位图保存为尽可能小的文件大小的好方法,这就是我想要 8 位 PNG 的原因。

我的问题是:如何将此位图作为 8 位 PNG 保存到文件/字节数组/流中?有什么好的图书馆吗?

最佳答案

您可以使用 nQuant(which you can install with nuget,或参阅下面的引用资料)执行此操作。以下示例转换磁盘上的图像,并且可以很容易地进行调整以满足您的需要。

    public static bool TryNQuantify(string inputFilename, string outputFilename)
{
var quantizer = new nQuant.WuQuantizer();
var bitmap = new Bitmap(inputFilename);
if (bitmap.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{
ConvertTo32bppAndDisposeOriginal(ref bitmap);
}

try
{
using (var quantized = quantizer.QuantizeImage(bitmap))
{
quantized.Save(outputFilename, System.Drawing.Imaging.ImageFormat.Png);
}
}
catch
{
return false;
}
finally
{
bitmap.Dispose();
}
return true;
}

private static void ConvertTo32bppAndDisposeOriginal(ref Bitmap img)
{
var bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (var gr = Graphics.FromImage(bmp))
gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
img.Dispose();
img = bmp;
}

有关详细信息,请参阅:

关于c# - 另存为 8 位 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27060236/

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