Monday, April 11, 2011

Remove transparency in images with C#

Hello there,

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

From stackoverflow
  • 1) Create a bitmap with a white background and with the same size as your image
    2) Load you image and paint it on top of your "white" bitmap
    3) Save the newly created image

  • 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 RemTransp(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");
    }
    
    Guffa : Insterad of drawing a rectangle, you could just call g.Clear(Color.White);
    Jörg B. : Awesome - thanks for the quick reply! For some reason I had to specify the width and height for the g.DrawImage, too... otherwise the placed pictures where for some reason smaller than their original .width/.height)
  • PNGs have alpha channel, so simple recoloring won't do. Create white image of same size, and create composite image overlay your image over it.

0 comments:

Post a Comment