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

GraalVM 21中Robot.createScreenCapture生成放大截图问题及临时修复咨询

Java屏幕截图GraalVM原生镜像缩放问题修复

问题根源

GraalVM原生镜像在Windows高DPI环境下的AWT处理逻辑与标准JVM存在差异:尽管代码能正确获取屏幕物理尺寸,但Robot.createScreenCapture会依据系统缩放比例(如150%、200%)捕获放大后的画面,最终导致生成的JPG尺寸超出预期,而Jar版本则能正常适配高DPI缩放。

临时修复方案

1. 手动缩放捕获图像

利用已正确获取的屏幕尺寸,将捕获的图像缩放到目标大小,修正缩放偏差:

static BufferedImage shotPicture(Rectangle size) {
    try {
        BufferedImage capturedImg = new Robot().createScreenCapture(size);
        // 对比捕获图像与目标尺寸,不一致则缩放
        if (capturedImg.getWidth() != size.width || capturedImg.getHeight() != size.height) {
            BufferedImage scaledImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = scaledImg.createGraphics();
            // 设置插值方式保证缩放画质
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(capturedImg, 0, 0, size.width, size.height, null);
            g2d.dispose();
            return scaledImg;
        }
        return capturedImg;
    } catch (AWTException ex) {
        ex.printStackTrace();
        return null;
    }
}

2. 配置程序高DPI感知

通过Windows应用清单声明高DPI感知,让原生镜像正确识别系统缩放比例:

  • 创建app.manifest文件,内容如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <application xmlns="urn:schemas-microsoft-com:asm.v3">
        <windowsSettings>
            <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>
        </windowsSettings>
    </application>
</assembly>
  • 编译原生镜像时指定该清单:
native-image -jar your-jar-file.jar --manifest app.manifest

3. 调整GraalVM编译参数

添加编译参数强制原生镜像启用完整的AWT相关服务,适配高DPI环境:

native-image -jar your-jar-file.jar --enable-all-security-services -H:+AddAllCharsets -H:EnableURLProtocols=http,https

验证方法

修改代码或编译参数后,重新生成原生镜像并运行,检查输出的out.jpg尺寸是否与屏幕物理尺寸一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 22:23:13