java进行屏幕截图


myScreenShot.java
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class myScreenShot {

    public static void main(String[] args) throws AWTException{
        String fileName = "mypic";    //是个文件夹名字
        screenShot(fileName);
    }

    public static final Logger logger = LogManager.getLogger(myScreenShot.class);


    public static String screenShot(String fileName) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();//获取屏幕大小
        Rectangle screenRectangle = new Rectangle(screenSize);//根据屏幕大小创建一个矩形
        String randomName = UUID.randomUUID().toString().replace("-", "");
        String name = randomName + ".png";//jpg等也可
        // 截图保存的路径
        File screenFile = new File(fileName);
        if (!screenFile.exists()) {
            screenFile.mkdirs();//创建文件路径
        }
        Robot robot;
        String path = "";
        boolean b = false;
        try {
            robot = new Robot();
            BufferedImage image = robot.createScreenCapture(screenRectangle);//使用Robot类提供的截屏方法,
            File f = new File(screenFile, name);
            b = ImageIO.write(image, "png", f);
        } catch (Exception e) {

            logger.error("error : ", e);
        }

        if (b) {
            path = fileName + File.separator + name;
        }
        return path;
    }
}

 

原创文章,作者:745907710,如若转载,请注明出处:https://blog.ytso.com/272331.html

(0)
上一篇 2022年7月9日
下一篇 2022年7月9日

相关推荐

发表回复

登录后才能评论