47

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
DaveS
  • 895
  • 1
  • 8
  • 20

1 Answers1

87
// 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
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 6
    for anyone reading about this question in the future, I also found it helpful to set the resolution of the bitmap object before declaring the graphics object: b.SetResolution (myImage.HorizontalResolution, myImage.VerticalResolution); This will avoid some scaling issues during the conversion – DaveS Jun 29 '11 at 15:32
  • How do I use the opposite, i.e. I want to move all my JPG images to PNG and all the whites should be replaced with transparent. – Shimmy Weitzhandler Nov 15 '11 at 02:53
  • 3
    @Shimmy: `Bitmap.SetTransparencyKey(Color.White)`. The saving part is easy, though - the image can be loaded in exactly the same way, and just change `ImageFormat.Jpeg` to `ImageFormat.Png`. – Ry- Nov 15 '11 at 03:50
  • 2
    OMG I used [this](http://stackoverflow.com/questions/3382683/convert-transparent-png-in-color-to-single-color/3382770#3382770) long solution. Anyway the function name is `Bitmap.MakeTransparent`. Thank you so much. – Shimmy Weitzhandler Nov 15 '11 at 04:24
  • 1
    @DaveS -- Setting the resolution is a good suggestion -- feel free to edit the answer. – Jay Elston Oct 16 '13 at 01:02