我目前正在开发一个需要更改BufferedImage中某些颜色的应用程序。(例如将黑色变为红色)
当我使用BufferedImage类的setRGB方法时,我注意到了一些奇怪的行为。
除非指定的RGB值已经在图像中出现过,否则setRGB将只是将其设置为完全透明的像素。
显然的解决方法是将所有所需的颜色都放在图像中,但有人能解释一下这是为什么吗?或者如何修复它?谢谢。
当我使用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”。