将 PNG 转换为 GIF 或 JPG

Convert PNG to GIF or JPG

我正在尝试将 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。 我使用 link 中提到的代码片段将背景设置为白色:

        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 看起来像这样:

类似于 (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"); 
}