我想让我的Java程序将实际屏幕与图片进行比较(截图)。
我不知道是否可能,但我已经在Jitbit(宏录制器)中看到了它,我想自己实现它。 (也许用这个例子你明白我的意思)。
由于
---- -----编辑 换句话说,是否可以检查图像是否显示?要查找并比较屏幕中的像素?
答案 0 :(得分:1)
您可以分两步完成此操作:
使用awt.Robot
创建屏幕截图BufferedImage image = new Robot().createScreenCapture(new Rctangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "png", new File("/screenshot.png"));
使用类似的内容比较屏幕截图:How to check if two images are similar or not using openCV in java?
答案 1 :(得分:1)
查看Sikuli项目。他们的自动化引擎基于图像比较。
我想,在内部,他们仍在使用OpenCV来计算图像相似度,但是有很多OpenCV Java绑定,例如this,允许从Java这样做。
项目源代码位于:https://github.com/sikuli/sikuli
答案 2 :(得分:1)
好的,所以几天后我找到了答案。
此方法采用屏幕截图:
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";
}
}
答案 3 :(得分:1)
您可以尝试aShot:documentation link
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
}
}