Jer*_*ov2 3 java bufferedimage replace image colors
所以我有一个有火山的图像文件.其他一切都是0xFFFF00FF(不透明洋红色).我想用0(透明)替换包含该颜色的每个像素.到目前为止我的方法看起来像这样:
public static BufferedImage replace(BufferedImage image, int target, int preferred) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage newImage = new BufferedImage(width, height, image.getType());
int color;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
color = image.getRGB(i, j);
if (color == target) {
newImage.setRGB(i, j, preferred);
}
else {
newImage.setRGB(i, j, color);
}
}
}
return newImage;
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但似乎很慢.我见过有人这样做,但我不知道发生了什么.如果有人知道更好的方法,我非常想听听.
虽然我还没有机会彻底测试这个,但使用LookupOp可能会从加速中受益:
public class ColorMapper
extends LookupTable {
private final int[] from;
private final int[] to;
public ColorMapper(Color from,
Color to) {
super(0, 4);
this.from = new int[] {
from.getRed(),
from.getGreen(),
from.getBlue(),
from.getAlpha(),
};
this.to = new int[] {
to.getRed(),
to.getGreen(),
to.getBlue(),
to.getAlpha(),
};
}
@Override
public int[] lookupPixel(int[] src,
int[] dest) {
if (dest == null) {
dest = new int[src.length];
}
int[] newColor = (Arrays.equals(src, from) ? to : src);
System.arraycopy(newColor, 0, dest, 0, newColor.length);
return dest;
}
}
Run Code Online (Sandbox Code Playgroud)
使用它就像创建LookupOp一样简单:
Color from = Color.decode("#ff00ff");
Color to = new Color(0, true);
BufferedImageOp lookup = new LookupOp(new ColorMapper(from, to), null);
BufferedImage convertedImage = lookup.filter(image, null);
Run Code Online (Sandbox Code Playgroud)