【发布时间】:2020-04-16 12:14:45
【问题描述】:
我正在尝试将 png 图像转换为 gif 和 jpg 格式。我正在使用在 Microsoft documentation 找到的代码。
我通过将此代码修改为以下代码创建了git-hub example:
public static void Main(string[] args)
{
// Load the image.
using (Image png = Image.FromFile("test-image.png"))
{
var withBackground = SetWhiteBackground(png);
// Save the image in JPEG format.
withBackground.Save("test-image.jpg");
// Save the image in GIF format.
withBackground.Save("test-image.gif");
withBackground.Dispose();
}
}
private static Image SetWhiteBackground(Image img)
{
Bitmap imgWithBackground = new Bitmap(img.Width, img.Height);
Rectangle rect = new Rectangle(Point.Empty, img.Size);
using (Graphics g = Graphics.FromImage(imgWithBackground))
{
g.Clear(Color.White);
g.DrawImageUnscaledAndClipped(img, rect);
}
return imgWithBackground;
}
所以我的问题: 有没有办法从 png 中获取看起来相同的 gif 格式?
编辑: Hans Passant 指出问题的根源在于透明背景。 经过一番挖掘,我找到了答案here。 我使用链接中提到的代码将背景设置为白色:
private Image SetWhiteBackground(Image img)
{
Bitmap imgWithBackground = new Bitmap(img.Width, img.Height);
Rectangle rect = new Rectangle(Point.Empty, img.Size);
using (Graphics g = Graphics.FromImage(imgWithBackground))
{
g.Clear(Color.White);
g.DrawImageUnscaledAndClipped(img, rect);
}
return imgWithBackground;
}
【问题讨论】:
-
有时 GDI 在转换图像时会出现问题。你试过像 ImageSharp 这样的库吗?
-
png 是不寻常的,它是透明背景上的黑色文本。只有二维码的中心有白色像素。 JPEG 不支持透明度,并且 GIF 编码器不允许您选择透明度颜色,因此您最终会得到黑色背景上的黑色文本。解决方法是提供明确定义的背景,使用 Graphics.DrawImage() 在清除为白色的位图上绘制此图像。但实际上你会考虑从源头上解决问题,透明背景上的黑色文本是一个错误。