views:

74

answers:

2

How to convert a white background of an image into a transparent background? Can anyone tel me how to do this?

+1  A: 

The first result from Google is this:

Make a color transparent http://www.rgagnon.com/javadetails/java-0265.html

It makes the Blue part of an image transparent, but I'm sure you can adapt that to use White intstead

(hint: Pass Color.WHITE to the makeColorTransparent function, instead of Color.BLUE)

Found a more complete and modern answer here: http://stackoverflow.com/questions/665406/how-to-make-a-color-transparent-in-a-bufferedimage-and-save-as-png

tim_yates
+1 for the hint. We wouldn't want to confuse SWDeveloper.
Gilbert Le Blanc
Hi tim, thanks for ur reply, I have tried that code with white instead of blue, but i am not getting a transparent image, the image background color is filled with black color. FYI - I didnt use applet instead I have used "ImageIO.write" and written it as image.png, tried with gif too.
SWDeveloper
Found this as well http://stackoverflow.com/questions/665406/how-to-make-a-color-transparent-in-a-bufferedimage-and-save-as-png
tim_yates
I think your 'black background' problem is not creating a new BufferedImage with TYPE_INT_ARGB to copy the filtered image into (ie: you're copying the image into a BufferedImage with doesn't support transparency)
tim_yates
Wow, u r right, its working... But one small issue, its not completely transparent, some pixels near outline of the image is still white.
SWDeveloper
They're not 100% white... :-/
tim_yates
Rather than doing `if ( ( rgb | 0xFF000000 ) == markerRGB ) {`, you'd need to check for the colour being within a certain range
tim_yates
Can u pls explain me little more...
SWDeveloper
A: 

Here is my solution. This filter will remove the background from any image as long as the background image color is in the top left corner.

private static class BackgroundFilter extends RGBImageFilter{

    boolean setUp = false;
    int bgColor;

    @Override
    public int filterRGB(int x, int y, int rgb) {
        int colorWOAlpha = rgb & 0xFFFFFF;
        if( ! setUp && x == 0 && y == 0 ){
            bgColor = colorWOAlpha;
            setUp = true;
        }
        else if( colorWOAlpha == bgColor )
            return colorWOAlpha;
        return rgb;
    }
}

Elsewhere...

ImageFilter bgFilter = new BackgroundFilter();
ImageProducer ip = new FilteredImageSource(image.getSource(), bgFilter);
image = Toolkit.getDefaultToolkit().createImage(ip);
Bob