I am trying to convert png image to gif and jpg format. I am using the code that I've found at Microsoft documentation.
I've created git-hub example by modifying this code into this:
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;
}
Original image (fictional data) is this:
And when I convert it to gif I get this:
So my question: is there a way to get gif format out of png that would look the same?
Edit: Hans Passant pointed out that the root problem was transparent background. After some digging I found answer here. I used code snipped mentioned in the link to set background to white:
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;
}
Something like (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");
}