Search code examples
c#.netimagetransparency

Remove transparency in images with C#


does anyone know a smooth / fast way of removing transparency from e.g. pngs/tiffs etc and replacing it with a white background?

Basically what I need this for is I need to create PDF/A compatible images, which may, according to the spec, have -no- transparency (and therefore a fixed white background is fine).

Any ideas / suggestions?

Cheers & thanks, -Jörg


Solution

  • You could create a bitmap the same size as the png, draw a white rectangle and then draw the image on top of it.

    void RemoveImageTransparancy(string file) {
        Bitmap src = new Bitmap(file);
        Bitmap target = new Bitmap(src.Size.Width,src.Size.Height);
        Graphics g = Graphics.FromImage(target);
        g.DrawRectangle(new Pen(new SolidBrush(Color.White)), 0, 0, target.Width, target.Height);
        g.DrawImage(src, 0, 0);
        target.Save("Your target path");
    }