Question

Using ImageFilter, how can we filter multiple colors in Java?

In this article.

http://www.javaworld.com/article/2074105/core-java/making-white-image-backgrounds-transparent-with-java-2d-groovy.html

He successfully filtered the WHITE color (RGB - 255, 255, 255).

public static Image makeColorTransparent(final BufferedImage im, final Color color)
{
  final ImageFilter filter = new RGBImageFilter()
  {
     // the color we are looking for (white)... Alpha bits are set to opaque
     public int markerRGB = color.getRGB() | 0xFFFFFFFF;

     public final int filterRGB(final int x, final int y, final int rgb)
     {
        if ((rgb | 0xFF000000) == markerRGB)
        {
           // Mark the alpha bits as zero - transparent
           return 0x00FFFFFF & rgb;
        }
        else
        {
           // nothing to do
           return rgb;
        }
     }
  };

  final ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
  return Toolkit.getDefaultToolkit().createImage(ip);
}
}

I want to filter related colors because the background of our images doesn't have a perfect white background - RGB(255, 255, 255).

It has different combinations of RGB for white like RGB(250, 251, 255), RGB (253, 255, 241), etc.

You may not notice this using our naked eyes, but if we are going to use Digital Color Meter or any tool that may inspect the image, we can notice the difference.

Is it possible to filter multiple colors? Any suggestions.

Thanks in advance.

Was it helpful?

Solution

There are multiple ways you could do this depending on what you want

I would suggest you create a method that determines what colours need to be filtered

if (filterColour(rgb)){
...
}


// method one predefine a set of colours that are near white
// suitable if you do not have too many colours or colors you want to
// filter are distinct from one another
private boolean filterColour(int rgb){
     return whiteishColours.contains(rgb);
}


//method two convert to HSV then use brightness and saturation to determine
//a zone of colours to filter
//I have not merged the components for this
private boolean filterColour(int r, int g, int b){
    float[] hsv = new float[3];
    Color.RGBtoHSB(r,g,b,hsv);
    return (hsv[2] > 0.9 && hsv.[1] < 0.1);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top