gpt4 book ai didi

java - 如何在 Java 中测试缓冲图像的像素的某种颜色

转载 作者:行者123 更新时间:2023-12-02 05:00:21 26 4
gpt4 key购买 nike

我正在尝试截取屏幕截图,然后在其中查找具有特定颜色的像素。首先,我尝试在某个 xy 坐标处打印图像的颜色,但我什至无法做到这一点。我做错了什么?

static int ScreenWidth;
static int ScreenHeight;
static Robot robot;

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic
callibrateScreenSize();
findSquares();
//takeScreenShot();

try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}

}

public static void callibrateScreenSize() {

try {
Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
ScreenWidth = captureSize.width;
ScreenHeight = captureSize.height;
System.out.println("Width is " + ScreenWidth);
System.out.println("Height is " + ScreenHeight);
} catch (Exception e) {
e.printStackTrace();
}
//return null;
}

public static BufferedImage takeScreenShot() {
Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage image = robot.createScreenCapture(captureSize);
return image;
}

public static void findSquares() {
System.out.println(takeScreenShot().getRGB(5,5));
}

谢谢!

最佳答案

您可以使用 BufferedImage#getRGBbyte[] Pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData() 来获取像素数据。 getRBG 更方便,但通常比获取像素数组慢

getRGB 将像素数据打包到 int 中,getData 将返回数组每个条目中的 RGB(A) ( >R = n; G = n+1; B=n+2(, A=n+3)),因此需要自己处理

您可以使用java.awt.Color,它允许您访问颜色的RGB值,将其打包为int值或转换 intColor

Color color = new Color(bufferedImage.getRGB(0, 0), true);
int redColor = Color.RED.getRGB();

this question的答案提供了处理byte[]像素数据

的示例

基本上,您需要循环数据,将图像中的值与您想要的值进行比较,直接比较(比较红色、绿色和蓝色值)或间接比较打包的 intColor 值。

就我个人而言,我会获取像素数据,将每个元素转换为 int 并将其与之前从 Color 打包的 int 进行比较> object,这会创建更少数量的短期对象,并且应该相当高效

您可以看看this answer它使用 getRGB 从给定像素获取红、绿、蓝值

关于java - 如何在 Java 中测试缓冲图像的像素的某种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com