【问题标题】:Convert PNG to GIF or JPG将 PNG 转换为 GIF 或 JPG
【发布时间】: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;
        }

原图(虚构数据)是这样的:

当我将它转换为 gif 时,我得到了这个:

所以我的问题: 有没有办法从 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;
        }

所以现在 gif 看起来像这样:

【问题讨论】:

  • 有时 GDI 在转换图像时会出现问题。你试过像 ImageSharp 这样的库吗?
  • png 是不寻常的,它是透明背景上的黑色文本。只有二​​维码的中心有白色像素。 JPEG 不支持透明度,并且 GIF 编码器不允许您选择透明度颜色,因此您最终会得到黑色背景上的黑色文本。解决方法是提供明确定义的背景,使用 Graphics.DrawImage() 在清除为白色的位图上绘制此图像。但实际上你会考虑从源头上解决问题,透明背景上的黑色文本是一个错误。

标签: c# qr-code


【解决方案1】:

类似(https://docs.sixlabors.com/articles/imagesharp/gettingstarted.html):

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"); 
} 

【讨论】:

猜你喜欢
  • 2012-09-15
  • 2012-01-25
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 2012-12-21
  • 2012-04-09
相关资源
最近更新 更多