1

Is it possible to get the Color of a specific pixel of an Image?

I know how to get it from a BufferedImage:

Color color = new Color(bufferedImage.getRGB(x, y));

But that doesn't work with a java.awt.Image that looks for example like this:

Image image = null;
try {
    image = ImageIO.read(new File("image.png"));
} catch (IOException e) {
    e.printStackTrace();
}

Is there a way of doing it? Thanks in advance!

  • 1
    [ImageIO.read returns a BufferedImage.](https://docs.oracle.com/javase/9/docs/api/javax/imageio/ImageIO.html#read-java.io.File-) – VGR Nov 26 '17 at 19:48
  • @VGR But I can initialize an `Image` that way... –  Nov 26 '17 at 19:50
  • 1
    Yes, polymorphism allows you to *refer* to it as an Image, or an Object, or even as a Transparency instance. But regardless of whether your code treats it like an Image, it is actually a BufferedImage. – VGR Nov 26 '17 at 19:51
  • @VGR But shouldn't it work than?! –  Nov 26 '17 at 19:54
  • Change `Image` to `BufferedImage` or `((BufferedImage) image).getRGB(x, y)` – Jared Rummler Nov 26 '17 at 19:55
  • If your `image` variable is declared as `BufferedImage image`, it will. If you declare it to be of type `Image`, it will still be a BufferedImage when the program *runs,* but the *compiler* doesn’t run the program. The compiler only knows that you have a variable of type Image in your code, and the Image class does not have a [getRGB](https://docs.oracle.com/javase/9/docs/api/java/awt/image/BufferedImage.html#getRGB-int-int-) method. – VGR Nov 26 '17 at 19:57
  • @JaredRummler I know that I could Change the `Image` to a `BufferedImage`, But in my code it has to be an `Image`. And I tryed to cast it to a `BufferedImage`, but it didn't wort. I get this error: `java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage` –  Nov 26 '17 at 19:59

1 Answers1

0

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

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

Jared Rummler
  • 37,824
  • 19
  • 133
  • 148