缓冲图像颜色操作

3
我目前正在开发一个需要更改BufferedImage中某些颜色的应用程序。(例如将黑色变为红色)
当我使用BufferedImage类的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”类被我的程序用来“高效地”存储BufferedImages。
  • 以下方法都在“Texture”类中。
  • “TextureColour”类存储了使用getRGB(x, y)从另一个包含颜色的BufferedImage生成的RGB值。这样做是为了避免RGB值混淆,并允许在不更改代码的情况下更改颜色。
  • getColour(x, y)消息根据BufferedImage.getRGB(x, y)给出的结果返回“TextureColour”。
2个回答

1
我猜测该图像使用的是索引颜色模型,因此只能绘制已经存在于图像中的颜色。尝试使用TYPE_INT_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;

我希望这可以解决您的问题,没有您的图像数据在本地很难复现...

1
请注意setRGB文档指出:“对于使用IndexColorModel的图像,会选择最接近颜色的索引。”
在您的包装类中,您的BufferedImages是否可能是索引类型?如果是这样,您可能需要在操作之前从现有的图像创建一个新的BufferedImage,其类型为TYPE_INT_ARGB而不是索引类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接