我试图将BufferedImage
中的所有黑色像素设置为特定的颜色,但它总是将其设置为白色,不管我输入了什么颜色。但是,如果color
变量是黑色的,那么它将设置为黑色。
BufferedImage spritesheet =
ImageIO.read(Text.class.getResourceAsStream("/HUD/font.gif"));
for(int xx = 0; xx < spritesheet.getWidth(); xx++) {
color = new Color(200, 180, 110);
for(int yy = 0; yy < spritesheet.getHeight(); yy++) {
if(spritesheet.getRGB(xx, yy) == new Color(0, 0, 0).getRGB())
spritesheet.setRGB(xx, yy, color.getRGB());
}
}
我做错了什么?
发布于 2014-03-08 05:38:52
吉姆·加里森是对的。当您加载GIF时,它的托盘中有一组有限的颜色,黑白两种颜色。当您用非黑色设置像素时,它使用托盘中最接近的颜色,并将其设置为白色。避免这种情况的一种方法是停止重复使用相同的BufferedImage进行写入,并创建一个全新的BufferedImage来保存,如下所示:
public static void main(String[] args) throws IOException
{
BufferedImage spritesheet =
ImageIO.read(new FileInputStream("/tmp/GYBOD.gif"));
BufferedImage copy = new BufferedImage(spritesheet.getWidth(), spritesheet.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
for(int xx = 0; xx < spritesheet.getWidth(); xx++) {
Color color = new Color(200, 180, 110);
for(int yy = 0; yy < spritesheet.getHeight(); yy++) {
if(spritesheet.getRGB(xx, yy) == new Color(0, 0, 0).getRGB()) {
//spritesheet.setRGB(xx, yy, color.getRGB());
copy.setRGB(xx, yy, color.getRGB());
}
else {
copy.setRGB(xx, yy, spritesheet.getRGB(xx,yy));
}
}
}
ImageWriter writer = ImageIO.getImageWritersBySuffix("gif").next();
writer.setOutput(ImageIO.createImageOutputStream(new FileOutputStream("/tmp/test.gif")));
writer.write(copy);
}
}
然后,当您保存GIF时,Java框架将查看ImageIO并使用新的颜色创建一个更广泛的托盘。
https://stackoverflow.com/questions/22265113
复制相似问题