False color image in Java from stack

272 Views Asked by At

I have 3 greyscale images I want to colourise, I asked a similar question last week and took the advice there, I have the below code which reads the RGB values for each pixel in the image. I want to do this for each individual image i.e. 1st image read red pixel value, 2nd image read blue pixel value and 3rd image read green pixel value and create a new image from that. I tried repeating the code 3 times but it just seemed to apply it to one pixel and keep repeating it but I couldnt find out why; I essentially copy and pasted the code 3 times but im sure theres a shorter and easier way, just not sure what!

Im reading the image using the following:

public static void main(final String args[])
    throws IOException
{
    File file = new File("src/resources/rgb.jpg");
    BufferedImage src = ImageIO.read(file);
    BufferedImage image = toBufferedImage(src);
    save(image, "png");
}

private void img1(BufferedImage image, BufferedImage src) {
    for (int x = 0; x < image.getWidth(); x++) {
        for (int y = 0; y < image.getHeight(); y++) {

            int clr = src.getRGB(x, y);
            int red = (clr & 0x00ff0000) >> 16;
            //int green = (clr & 0x0000ff00) >> 8;
            //int blue = clr & 0x000000ff; 

        }
    }
}

So I essentially need to repeat the code 3 times and then create a new image from the result. Just wondering if anyone could help?

Thanks in advance

1

There are 1 best solutions below

3
On

Pull your double for loop out into a method (not sure exactly how you want it to work):

private void doStuffToImage(Image image, Image src) {
  for (int x = 0; x < image.getWidth(); x++) {
    for (int y = 0; y < image.getHeight(); y++) {
      final int clr = src.getRGB(x, y);
      final int red = (clr & 0x00ff0000) >> 16;
      final int green = (clr & 0x0000ff00) >> 8;
      final int blue = clr & 0x000000ff;
    }
  }
}

Also, ditch all the finals.