Java Graphics How to - Convert buffered image to RGB color value








Question

We would like to know how to convert buffered image to RGB color value.

Answer

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
// ww  w . j  av  a 2s.  co m
import javax.imageio.ImageIO;

public class Main {
  public static void main(String[] args) throws IOException {
    InputStream stream = Main.class.getResourceAsStream("test.png");
    BufferedImage image = ImageIO.read(stream);
    int iw = image.getWidth();
    int ih = image.getHeight();
    stream.close();

    for (int y = 0; y < ih; y++) {
      for (int x = 0; x < iw; x++) {
        int pixel = image.getRGB(x, y);
        int alpha = (pixel >> 24) & 0xFF;
        int red = (pixel >> 16) & 0xFF;
        int green = (pixel >> 8) & 0xFF;
        int blue = pixel & 0xFF;
      }
    }
  }
}