java实现屏幕截图

话不多说直接上代码

  /**
     * 屏幕截图
     *
     * @param imageName 存储图片名称  比如: screen
     * @param path      图片路径 比如: C:\Users\NineSun\Desktop\java实现屏幕截图\
     * @param imgType   图片类型 png 或 jpg
     * @throws AWTException
     * @throws IOException
     */
    public static String cutPic(String imageName, String path, String imgType) throws AWTException, IOException {
        System.out.println("开始截图");
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(screenRectangle);
        //首先创建一个目录
        File file = new File(path);
        if (!file.isDirectory() || !file.exists()) {
            file.mkdir();
        }
        //判断文件是否存在,存在就改名字
        String fileName = imageName + "." + imgType;
        ImageIO.write(image, imgType, new File(path + fileName));
        String filePath = path + fileName;
        return filePath;
    }

如何使用:

   public static void main(String[] args) throws IOException, AWTException {
        cutPic("test", "C:\\Users\\NineSun\\Desktop\\cd\\", "png");
    }

如果我们运行时出现java.awt.HeadlessException: null这种错误,解决方式如下:

  • 1.在idea中运行:
    在这里插入图片描述

在这里插入图片描述

输入:

-Djava.awt.headless=false
  • 2.如果我们需要打包运行,则需要我们修改主配置类,修改成以下内容:
@SpringBootApplication
public class ScreenShareApplication {

    public static void main(String[] args) {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(ScreenShareApplication.class);
        builder.headless(false).run(args);
    }
}

至此,实现屏幕截图的功能就结束了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZNineSun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值