是否可以获取 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();
}
有办法吗?提前谢谢!
答案 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?