C# 将PNG转换为GIF或JPG
我正在尝试将png图像转换为gif和jpg格式。我正在使用我在上找到的代码 我通过将此代码修改为以下内容创建:C# 将PNG转换为GIF或JPG,c#,qr-code,C#,Qr Code,我正在尝试将png图像转换为gif和jpg格式。我正在使用我在上找到的代码 我通过将此代码修改为以下内容创建: publicstaticvoidmain(字符串[]args) { //加载图像。 使用(Image png=Image.FromFile(“test Image.png”)) { var withBackground=SetWhiteBackground(png); //以JPEG格式保存图像。 withBackground.Save(“testimage.jpg”); //以GIF
publicstaticvoidmain(字符串[]args)
{
//加载图像。
使用(Image png=Image.FromFile(“test Image.png”))
{
var withBackground=SetWhiteBackground(png);
//以JPEG格式保存图像。
withBackground.Save(“testimage.jpg”);
//以GIF格式保存图像。
withBackground.Save(“test image.gif”);
withBackground.Dispose();
}
}
私有静态图像集WhiteBackground(图像img)
{
位图imgWithBackground=新位图(img.Width、img.Height);
矩形rect=新矩形(Point.Empty,img.Size);
使用(Graphics g=Graphics.FromImage(imgWithBackground))
{
g、 清晰(颜色:白色);
g、 DrawImageUnscaledClipped(img,rect);
}
返回imgWithBackground;
}
原始图像(虚构数据)如下所示:
当我将其转换为gif时,我得到:
因此,我的问题是:
有没有一种方法可以让gif格式的png看起来一样
编辑:
汉斯·帕桑指出,根本问题是背景透明。
经过一番挖掘,我找到了答案。
我使用链接中提到的代码截取将背景设置为白色:
private Image SetWhiteBackground(图像img)
{
位图imgWithBackground=新位图(img.Width、img.Height);
矩形rect=新矩形(Point.Empty,img.Size);
使用(Graphics g=Graphics.FromImage(imgWithBackground))
{
g、 清晰(颜色:白色);
g、 DrawImageUnscaledClipped(img,rect);
}
返回imgWithBackground;
}
现在gif看起来像这样:
类似()的内容:
有时GDI在转换图像时遇到问题。你试过像ImageSharp这样的库吗?png是不寻常的,它是透明背景上的黑色文本。只有二维码的中心有白色像素。JPEG不支持透明度,GIF编码器也不允许您选择透明度颜色,因此最终会在黑色背景上显示黑色文本。解决方法是提供定义良好的背景,使用Graphics.DrawImage()在清除为白色的位图上绘制此图像。但事实上,你会考虑在源上解决问题,透明背景上的黑文本是一个错误。欢迎你。如果被接受,请将其标记为答案,以便我们都得到一些分数:)
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
// Open the file and detect the file type and decode it.
// Our image is now in an uncompressed, file format agnostic, structure in-memory as a series of pixels.
using (Image image = Image.Load("test-image.png"))
{
// The library automatically picks an encoder based on the file extensions then encodes and write the data to disk.
image.Save("test.gif");
}