我目前正在研究需要更改BufferedImage中某些顏色的應用程序。 (例如黑色到紅色)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);
}
上的代碼的一些注意事項:
- 的「紋理」類由我的程序存儲BufferedImages「有效」。
- 以下方法在Texture類中。
- 'TextureColour'類存儲在另一個包含顏色的BufferedImage上使用getRGB(x,y)生成的RGB值。這樣做是爲了避免混淆RGB值,並允許在不更改代碼的情況下更改顏色。
- getColour(x,y)消息根據BufferedImage.getRGB(x,y)給出的結果返回'TextureColour'。