0

I'm working for a swing project and I have to display the same image multiple times, by changing pixels color every time.

For example : the first image must be displayed in blue and the second one must be displayed in orange, but the problem is that when the second one is displayed, it changes the color of the first one in orange, too. How can I display every image with its color ?

Thank you.

private void drawPixel(int index,String name) throws IOException {
    File input = new File("map-pointer-clipart-3.png");
    BufferedImage imagePointer = ImageIO.read(input);
    Graphics g = this.imagePoints.getGraphics();
    changeColorPixelLabel(imagePointer,labelClassesCount-1);
    int x = (index % this.width);
    int y = (index / this.width);
    g.drawImage(imagePointer,x-20, y-31,100,100, null);
    repaint();
}

private void changeColorPixelLabel(BufferedImage img, int index) {
    for(int i=0; i<img.getWidth(); i++) {
        for(int j=0; j<img.getHeight(); j++) {
            Color c = labelConstraintColor.get(index);
            if(img.getRGB(i, j) == new Color(255,255,255).getRGB()) {
                    img.setRGB(i, j, c.getRGB());
            }
        }
    }
}
kazrak
  • 3
  • 6

1 Answers1

1

Create a second instance of BufferedImage, paint the original image to it...

BufferedImage copy= new BufferedImage(imagePointer.getWidth(), imagePointer.getHeight(), BufferedImage.TYPE_ARGB);
Graphics2D g2d = copy.createGraphics();
g2d.drawImage(0, 0, imagePointer, null);
g2d.dispose();

And know you have a new copy which you can manipulate

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thank you for your answer, but it didn't match with my code. In fact everytime I have to create another image with a different color, the color of the last one is applied for the rest of images. I tried to put your code in a function which returns the copy of BuffererdImage and I put all the copies of this image in a Vector. But, it still exists a reference between the copies and the original image. – kazrak Jun 25 '17 at 16:27
  • Open a master image. Use this as the base template. When you need another copy, use the master template. If updating one is updating another, then your still doing something wrong – MadProgrammer Jun 25 '17 at 20:05
  • I tried your version but I think there is still a problem with all the copies I make. Every time I use an ImageIO.read all the copies of this image suffer the same modification. Maybe there is a problem because I use multiple copies of the same image? How can I display the same image multiple times but with no reference to the original? – kazrak Jun 28 '17 at 19:10