Compare image to actual screen

后端 未结 4 1222
萌比男神i
萌比男神i 2021-01-16 23:03

I\'d like to make my Java program compare the actual screen with a picture (screenshot).

I don\'t know if it\'s possible, but I have seen it in Jitbit (a macro recor

4条回答
  •  臣服心动
    2021-01-16 23:39

    Ok then, so I found an answer after a few days.

    This method takes the screenshot:

    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();
            }
        }
    

    And this other one will compare the images

    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";
        }
    }
    

提交回复
热议问题