You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java AWT Robot截图异常:局部截图与全屏子图像为何不一致?

java.awt.Robot截图像素不一致的原因

这是Java官方确认的已知Bug,Bug编号为JDK-8322845。

问题现象

使用java.awt.Robot分别截取全屏截图和屏幕某一局部区域截图后,局部截图与全屏截图对应坐标的子图像像素存在不一致的情况:

  • 多数场景下,测试代码会返回false,表明两个图像像素不匹配;
  • 仅在部分x、y、w、h参数取值时,会返回true。

测试代码

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ScreenCapTest {
    public static void main(String[] args) throws AWTException, IOException {
        // Construct Robot
        Robot r = new Robot();
        
        // Get dimensions of screen
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        
        // Take screenshot
        BufferedImage screen = r.createScreenCapture(new Rectangle(0,0, (int)screenSize.getWidth(), (int)screenSize.getHeight()));
        
        // Take screenshot of small section of screen
        int x = 5;
        int y = 5;
        int w = 50;
        int h = 50;
        BufferedImage subscreen = r.createScreenCapture(new Rectangle(x,y,w,h));
        
        // Create a subimage of the same section of the screen from the original screenshot
        BufferedImage subimageOfScreen = screen.getSubimage(x,y,w,h);
        
        // Are they equal?
        System.out.println(imgEqual(subimageOfScreen, subscreen));
        
        // Output images for comparison
        ImageIO.write(subimageOfScreen, "png", new File("subimage.png"));
        ImageIO.write(subscreen, "png", new File("subscreen.png"));
    }
    
    public static boolean imgEqual(BufferedImage image1, BufferedImage image2) {
        int width;
        int height;
        boolean imagesEqual = true;

        if( image1.getWidth()  == ( width  = image2.getWidth() ) && 
            image1.getHeight() == ( height = image2.getHeight() ) ){

            for(int x = 0;imagesEqual == true && x < width; x++){
                for(int y = 0;imagesEqual == true && y < height; y++){
                    if( image1.getRGB(x, y) != image2.getRGB(x, y) ){
                        imagesEqual = false;
                    }
                }
            }
        } else {
            imagesEqual = false;
        }
        return imagesEqual;
    }
}

示例对比图

  • 全屏截图的子图像:
    Subimage of the full screenshot

  • 同一区域的直接截图:
    Screenshot of the same portion of the screen

内容的提问来源于stack exchange,提问作者rupumped

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:17:36