Java Graphics How to - Loop through pixels in an image








Question

We would like to know how to loop through pixels in an image.

Answer

import java.awt.image.BufferedImage;
import java.net.URL;
//from  w ww  .  ja  va  2s  . c  o  m
import javax.imageio.ImageIO;

public class Main {
  public static void main(final String args[]) throws Exception {
    URL url = new URL("http://www.java2s.com/style/download.png");
    BufferedImage image = ImageIO.read(url);

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

        System.out.println("Red Color value = " + red);
        System.out.println("Green Color value = " + green);
        System.out.println("Blue Color value = " + blue);
      }
    }
  }
}

The code above generates the following result.