使用ImageFilter,我们如何在Java中过滤多种颜色?
在本文中。
他成功地过滤了WHITE颜色(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);
}
}
我想过滤相关的颜色,因为我们的图像背景没有完美的白色背景 - RGB(255,255,255)。
它具有不同的RGB白色组合,如RGB(250,251,255),RGB(253,255,241)等。
您可能不会用肉眼注意到这一点,但如果我们要使用数字色度计或任何可能检查图像的工具,我们可以注意到差异。
是否可以过滤多种颜色?任何建议。
提前致谢。
答案 0 :(得分:1)
根据您的需要,有多种方法可以做到这一点
我建议你创建一个方法来确定需要过滤的颜色
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);
}