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
2010-06-23 12:20:44
+1 for the hint. We wouldn't want to confuse SWDeveloper.
Gilbert Le Blanc
2010-06-23 12:31:36
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
2010-06-23 13:18:32
Found this as well http://stackoverflow.com/questions/665406/how-to-make-a-color-transparent-in-a-bufferedimage-and-save-as-png
tim_yates
2010-06-23 13:32:25
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
2010-06-23 13:33:41
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
2010-06-23 14:04:45
They're not 100% white... :-/
tim_yates
2010-06-23 14:06:50
Rather than doing `if ( ( rgb | 0xFF000000 ) == markerRGB ) {`, you'd need to check for the colour being within a certain range
tim_yates
2010-06-23 14:12:04
Can u pls explain me little more...
SWDeveloper
2010-06-23 14:55:22
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
2010-08-13 20:21:16