Convert Transparent PNG to JPG with Non-Black Back

2019-01-06 14:34发布

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?

1条回答
不美不萌又怎样
2楼-- · 2019-01-06 15:00
// 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
}
查看更多
登录 后发表回答