Конвертировать PNG в GIF или JPG - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь преобразовать изображение PNG в формат GIF и JPG. Я использую код, который я нашел в документации Microsoft .

Я создал git -hub пример , изменив этот код следующим образом:

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

Исходное изображение (вымышленные данные) выглядит так: Swiss bill with fictional data

И когда я преобразую его в gif, я получаю это: enter image description here

Итак, мой вопрос: есть ли способ получить формат gif из png, который бы выглядел одинаково?

Редактировать: Ганс Пассант указал, что root проблема была в прозрачном фоне. После некоторых копаний я нашел ответ здесь . Я использовал фрагмент кода, упомянутый в ссылке, чтобы установить белый фон:

        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 выглядит так: Gif image with white background

1 Ответ

1 голос
/ 16 апреля 2020

Что-то вроде (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"); 
} 
...