将图像与实际屏幕进行比较

我想让我的Java程序将实际屏幕与图片进行比较(截图)。

我不知道它是否可能,但我在Jitbit(一台宏录像机)中看过它,我想自己实现它。 (也许用那个例子你明白我的意思)。

谢谢

—-编辑—–换句话说,是否可以检查图像是否显示? 要查找并比较屏幕中的像素?

您可以分两步完成此操作:

  1. 使用awt.Robot创建屏幕截图

    BufferedImage image = new Robot().createScreenCapture(new Rctangle(Toolkit.getDefaultToolkit().getScreenSize())); ImageIO.write(image, "png", new File("/screenshot.png")); 
  2. 比较屏幕截图使用类似的东西: 如何在java中使用openCV检查两个图像是否相似?

看看Sikuli项目。 他们的自动化引擎基于图像比较。

我想,在内部他们仍然使用OpenCV来计算图像相似度,但是有很多像这样的OpenCV Java绑定,允许从Java这样做。

项目源代码位于: https : //github.com/sikuli/sikuli

好的,所以几天后我找到了答案。

此方法截取屏幕截图:

 public static void takeScreenshot() { try { BufferedImage image = new Robot().createScreenCapture(new Rectangle(490,490,30,30)); /* this two first parameters are the initial X and Y coordinates. And the last ones are the increment of each axis*/ ImageIO.write(image, "png", new File("C:\\Example\\Folder\\capture.png")); } catch (IOException e) { e.printStackTrace(); } catch (HeadlessException e) { e.printStackTrace(); } catch (AWTException e) { e.printStackTrace(); } } 

而另一个将比较图像

 public static String compareImage() throws Exception { // savedImage is the image we want to look for in the new screenshot. // Both must have the same width and height String c1 = "savedImage"; String c2 = "capture"; BufferedInputStream in = new BufferedInputStream(new FileInputStream(c1 + ".png")); BufferedInputStream in1 = new BufferedInputStream(new FileInputStream( c2 + ".png")); int i, j; int k = 1; while (((i = in.read()) != -1) && ((j = in1.read()) != -1)) { if (i != j) { k = 0; break; } } in.close(); in1.close(); if (k == 1) { System.out.println("Ok..."); return "Ok"; } else { System.out.println("Fail ..."); return "Fail"; } } 

您可以尝试aShot: 文档链接

1)aShot可以忽略您用特殊颜色标记的区域。

2)aShot可以提供显示图像之间差异的图像。

 private void compareTowImages(BufferedImage expectedImage, BufferedImage actualImage) { ImageDiffer imageDiffer = new ImageDiffer(); ImageDiff diff = imageDiffer .withDiffMarkupPolicy(new PointsMarkupPolicy() .withDiffColor(Color.YELLOW)) .withIgnoredColor(Color.MAGENTA) .makeDiff(expectedImage, actualImage); // areImagesDifferent will be true if images are different, false - images the same boolean areImagesDifferent = diff.hasDiff(); if (areImagesDifferent) { // code in case of failure } else { // Code in case of success } } 

要保存差异图像:

 private void saveImage(BufferedImage image, String imageName) { // Path where you are going to save image String outputFilePath = String.format("target/%s.png", imageName); File outputFile = new File(outputFilePath); try { ImageIO.write(image, "png", outputFile); } catch (IOException e) { // Some code in case of failure } }