How can I convert PNG to JPG in C #?

8

I'm working on an old project that uses ASP Site.

I need to convert PNG image to JPG.

How to do this?

Note : I do not want to rename the file, I want to transform the mime from image/png to image/jpeg .

    
asked by anonymous 24.11.2017 / 16:50

2 answers

8

One solution is to open the image and then save as JPG

Image png = Image.FromFile(@"C:\caminho-da-imagem.png");     
png .Save(@"C:\caminho-da-imagem.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

Note that this will cause the bottomless parts of the PNG to have the black color in the new image.

To avoid this, you will need to work on the original image.

The code below creates an instance of Bitmap with the dimensions of the original image, sets the resolution according to the original image, and then creates an instance of Graphics with the Graphics.FromImage .

With the instance of Graphics the entire surface is painted white (obviously you can do this with any color) using the Graphics.Clear and then the original image is" drawn "on top of the new one using the < a href="https://msdn.microsoft.com/en-us/library/8b0tzkb5(v=vs.110).aspx"> DrawImageUnscaled , the second and third parameter are referring to the position in which the image will be drawn, how we want a completely equal image, we use the position (0, 0).

Image png = Image.FromFile(@"C:\caminho-da-imagem.png");
using (var bitmap = new Bitmap(png.Width, png.Height)) 
{
    bitmap.SetResolution(png.HorizontalResolution, png.VerticalResolution);

    using (var g = Graphics.FromImage(b)) 
    {
        g.Clear(Color.White);
        g.DrawImageUnscaled(png, 0, 0);
    }

    bitmap.Save(@"C:\caminho-nova-imagem.jpg", ImageFormat.Jpeg);
}

I made a test using this image here

Click the image (or here) to see the lack of background a>

The first code, generated this image

Secondcode,generatedthisimage

    
24.11.2017 / 16:52
3

According to MSDN: link

Upload image:

System.Drawing.Image image1 = System.Drawing.Image.FromFile(@"C:\imagem-especifica.png");

Save as JPEG:

image1.Save(@"C:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

Save as GIF:

image1.Save(@"C:\test.gif", System.Drawing.Imaging.ImageFormat.Gif);

Save as PNG:

image1.Save(@"C:\test.png", System.Drawing.Imaging.ImageFormat.Png);

Extra

Assuming you are manipulating the image, for example you want to resize or adjust the quality, then it is likely that you will use Bitmap , in this case use using to prevent the file from being "open", for example:

System.Drawing.Image image1 = System.Drawing.Image.FromFile(@"C:\imagem-especifica.png");

using(var bmp = new Bitmap(image1))
{
    //Faz algo aqui
}

//Salva
image1.Save(@"C:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    
24.11.2017 / 16:52