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; } }
示例对比图
全屏截图的子图像:

同一区域的直接截图:

内容的提问来源于stack exchange,提问作者rupumped
相关产品推荐
相关产品推荐

