Posts Tagged transparent

Make image backgrounds transparent with tolerance

In one of the projects I am working on at the moment, I needed to convert the background colour of an image to be transparent so the image looks better on a non-white background.

Looking on the Web, I found the following article from Dustin Marx:
Making White Image Backgrounds Transparent with Java 2D/Groovy
If the link is broken, please download his code from the following link: ImageTransparency.java

The method which makes the background colour transparent is called makeColorTransparent. This method works pretty well, except in some cases as shown in the example below:

Original image Converted image
using Dustin’s method

This is actually quite normal. Indeed, his code is converting a specific colour (#FFFFFF in our case) to be transparent. But what if the background is not homogeneous?

This is the reason why I had to modify his method to add a new parameter called tolerance:

01private Image makeColorTransparent(final BufferedImage im, final Color color, int tolerance) {
02    int temp = 0;
03    if (tolerance < 0 || tolerance > 100) {
04        System.err.println("The tolerance is a percentage, so the value has to be between 0 and 100.");
05        temp = 0;
06    } else {
07        temp = tolerance * (0xFF000000 | 0xFF000000) / 100;
08    }
09    final int toleranceRGB = Math.abs(temp);
10         
11    final ImageFilter filter = new RGBImageFilter() {
12        // The color we are looking for (white)... Alpha bits are set to opaque
13        public int markerRGBFrom = (color.getRGB() | 0xFF000000) - toleranceRGB;
14        public int markerRGBTo = (color.getRGB() | 0xFF000000) + toleranceRGB;
15 
16        public final int filterRGB(final int x, final int y, final int rgb) {
17            if ((rgb | 0xFF000000) >= markerRGBFrom && (rgb | 0xFF000000) <= markerRGBTo) {
18                // Mark the alpha bits as zero - transparent
19                return 0x00FFFFFF & rgb;
20            } else {
21                // Nothing to do
22                return rgb;
23            }
24        }
25    };
26 
27    final ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
28    return Toolkit.getDefaultToolkit().createImage(ip);
29}

Such as Photoshop, the tolerance is a percentage value between 0 and 100. The higher the tolerance is, the bigger the range of colours will be.

Let’s take our previous example and apply a 50% tolerance:

That looks much better, isn’t it? 🙂

, , ,

3 Comments