如何获取图像特定像素的颜色? - Java

时间:2017-11-26 19:46:27

标签: java image colors rgb pixel

是否可以获取 Image 的特定像素的颜色?

我知道如何从BufferedImage

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

但这并不适用于 java.awt.Image ,例如:

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

有办法吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

ImageIO.read(file)应返回BufferedImage。您还可以使用PixelGrabber来获取特定颜色。例如:

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也有获取BufferedImage的方法,但可能会返回null:Why does ToolkitImage getBufferedImage() return a null?

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