Java 缓冲图像颜色处理

Java 缓冲图像颜色处理,java,colors,rgb,bufferedimage,Java,Colors,Rgb,Bufferedimage,我目前正在开发一个需要更改BuffereImage中某些颜色的应用程序。(例如,从黑色到红色) 在使用BuffereImage类的setRGB方法时,我注意到一些奇怪的行为 除非指定的RGB值已经在图像中的某个位置具有特征,否则setRGB将简单地将其设置为完全透明的像素 显而易见的解决办法是在图像中添加所有需要的颜色,但是有人能向我解释为什么会出现这种情况,或者如何修复它吗?谢谢 public Texture replaceColour(final TextureColour TARGET,

我目前正在开发一个需要更改BuffereImage中某些颜色的应用程序。(例如,从黑色到红色)

在使用BuffereImage类的setRGB方法时,我注意到一些奇怪的行为

除非指定的RGB值已经在图像中的某个位置具有特征,否则setRGB将简单地将其设置为完全透明的像素

显而易见的解决办法是在图像中添加所有需要的颜色,但是有人能向我解释为什么会出现这种情况,或者如何修复它吗?谢谢

public Texture replaceColour(final TextureColour TARGET, final TextureColour REPLACEMENT)
{
            /*
             * You needn't worry about this bit, just some checks my program
             * uses to determine if a similar image has already been created.
             */
    final String PATH = loadedTexturesFilenames.get(REFERENCE) + "!replacedColour:" + TARGET.RGB + ":" + REPLACEMENT.RGB;
    final Texture PATH_TEXTURE = getTexture(PATH);
    if (PATH_TEXTURE == null)
    {
                    /*
                     * This is where the color changing happens.
                     * See below for information on the 'Texture' and
                     * 'TextureColour' classes.
                     */
        final BufferedImage IMAGE = cloneImage(BUFFERED_IMAGE);
        for (int x = 0; x != IMAGE.getWidth(); x++)
        {
            for (int y = 0; y != IMAGE.getHeight(); y++)
            {
                if (getColour(x, y) == TARGET)
                {
                    IMAGE.setRGB(x, y, REPLACEMENT.RGB);
                }
            }
        }
        return new Texture(IMAGE, PATH);
    }
    else
    {
        return PATH_TEXTURE;
    }
}

public static BufferedImage cloneImage(final BufferedImage I) 
{
     ColorModel colour = I.getColorModel();
     boolean alpha = colour.isAlphaPremultiplied();
     WritableRaster writableRaster = I.copyData(null);
     return new BufferedImage(colour, writableRaster, alpha, null);
}
关于代码的一些注释:

  • 我的程序使用“Texture”类“高效”存储缓冲区图像
  • 以下方法位于纹理类中
  • “TextureColor”类在另一个包含颜色的BuffereImage上存储使用getRGB(x,y)生成的RGB值。这样做是为了避免RGB值的混淆,并允许在不更改代码的情况下更改颜色
  • GetColor(x,y)消息根据BuffereImage.getRGB(x,y)给出的结果返回“TextureColor”

我猜图像使用的是索引颜色模型,因此只能绘制图像中已经存在的颜色。尝试创建类型为\u INT \u ARGB的克隆映像。比如:

BufferedImage image = new BufferedImage(I.getWidth(), I.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
//draw original image I to the new graphics
g.dispose();
return image;
我希望这能解决您的问题,没有您的图像数据,很难在本地复制它。

请注意,“对于具有IndexColorModel的图像,将选择具有最近颜色的索引。”

在包装器类中,是否有任何方式可以使BuffereImage成为索引类型?如果是这样,在操作之前,您可能希望从现有的BuffereImage创建一个类型为_INT_ARGB而不是索引类型的新BuffereImage