Question

I'm trying to set all black pixels in a BufferedImage to a certain colour, but it always just sets it to white, no matter what colour I put in. However, if the color variable is black, then it will set it to black.

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());
     }
  }

What have I done wrong?

font

Was it helpful?

Solution

Jim Garrison is right. When you loaded the GIF, it has a limited set of colors in its pallet, black and white. When you set a pixel with a non-black color, it uses the closest color in the pallet and sets it to white. One way to avoid this is stop reusing the same BufferedImage to write as you did to read, and create a brand new BufferedImage to save, like this:

   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);

   }
}

Then when you save the GIF, Java ImageIO framework will look at the BufferedImage and create a more extensive pallet with your new colors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top