Stack Overflow archive
1 score

How to get the Color of a specific pixel of an Image? - Java

score
1
question views
2.3K
license
CC BY-SA 3.0

ImageIO.read(file) should return a BufferedImage. You can also use PixelGrabber to get a specific color. Example:

java
private static Color getSpecificColor(Image image, int x, int y) {
  if (image instanceof BufferedImage) {
    return new Color(((BufferedImage) image).getRGB(x, y));
  }
  int width = image.getWidth(null);
  int height = image.getHeight(null);
  int[] pixels = new int[width * height];
  PixelGrabber grabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
  try {
    grabber.grabPixels();
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  int c = pixels[x * width + y];
  int  red = (c & 0x00ff0000) >> 16;
  int  green = (c & 0x0000ff00) >> 8;
  int  blue = c & 0x000000ff;
  return new Color(red, green, blue);
}

ToolkitImage also has a method to get the BufferedImage but may return null: Why does ToolkitImage getBufferedImage() return a null?

http://www.rgagnon.com/javadetails/java-0257.html

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.