Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Transparent PNG to JPG with Non-Black Background Color

I'm using System.Drawing.Image in .Net to do a simple conversion from png to jpeg. I'm basically just using these two lines of code:

Image img = Image.FromFile(filename); img.Save(newFilename, System.Drawing.Imaging.ImageFormat.Jpeg); 

it works fine except for when the png files contain transparency due to the alpha channel. In which case the converted jpeg has a black background. Is there any way to make the background white instead?

like image 635
DaveS Avatar asked Jun 28 '11 22:06

DaveS


People also ask

How do I remove a black background from a PNG?

When a PNG image with a transparent background is selected from the Recent FIle selector and appears with a black background, the black background can be removed by re-uploading the image as a New File each time you use the image.

How do I convert a PNG to a JPEG without losing transparency?

Paint is a built-in Windows tool that you can use it to convert a PNG image to JPEG without losing quality. , open the PNG image with Paint. Open the PNG image with Paint and navigate to File > Save as > JPEG picture. Then, choose a location, add a name, and make sure the file format is set to JPEG.

How do I make a white background transparent in a JPEG?

You can create a transparent area in most pictures. Select the picture that you want to create transparent areas in. Click Picture Tools > Recolor > Set Transparent Color. In the picture, click the color you want to make transparent.


1 Answers

// Assumes myImage is the PNG you are converting using (var b = new Bitmap(myImage.Width, myImage.Height)) {     b.SetResolution(myImage.HorizontalResolution, myImage.VerticalResolution);      using (var g = Graphics.FromImage(b)) {         g.Clear(Color.White);         g.DrawImageUnscaled(myImage, 0, 0);     }      // Now save b as a JPEG like you normally would } 
like image 85
Ry- Avatar answered Sep 18 '22 12:09

Ry-