gpt4 book ai didi

java - 如何在 BufferedImage 中用另一种颜色替换颜色

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:55:12 24 4
gpt4 key购买 nike

所以我有一个图像文件,上面有一座火山。其他一切都是 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;
}

这工作正常但看起来很慢。我见过有人用另一种方式这样做,但我不知道发生了什么。如果有人知道更好的方法来做到这一点,我非常想听听。

最佳答案

虽然我还没有机会彻底测试它,但使用 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;
}
}

使用它就像创建 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);

关于java - 如何在 BufferedImage 中用另一种颜色替换颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27462758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com