自动捕获剪贴板数据并将其保存到文件中

时间:2014-04-16 10:53:03

标签: java

每当按下Print屏幕时从剪贴板捕获图像并使用java将其保存在文件(.doc)中

主要目的是从剪贴板复制数据并自动将其保存到本地磁盘而无需转到所需的程序(即MS Word) - 单击新建 - 按(Ctrl + V)粘贴并使用名称保存。

代码应自动执行上述所有三个步骤。

我的源代码

public class CaptureScreenShot {

    private static String DIR  ="C:\\QUIS\\";
    private static JTextField txtDocNumber;
    public static void main(String[] args) throws Exception{
        txtDocNumber = new JTextField();
        Robot robot = new Robot();


        Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
        int width = (int) d.getWidth();
        int height = (int) d.getHeight();

        robot.delay(5000);

        Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
                height));
        BufferedImage  bi = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);

        String fileNameToSaveTo = "C:/QUIS/screenCapture_" + createTimeStampStr() + ".PNG";
        String newFile = "C:/QUIS/x" + ".org";
        File newFilee = new File(newFile);

        writeImage(bi, fileNameToSaveTo, "PNG");

        System.out.println("Screen Captured Successfully and Saved to:\n"+fileNameToSaveTo);

        Desktop desktop = Desktop.getDesktop();  
        writeImage(bi, newFile, "org");
        desktop.open(newFilee); 
    }

    public static int writeImage(BufferedImage img, String fileLocation,
            String extension) {
        try {
            BufferedImage bi = img;
            File outputfile = new File(fileLocation);
            ImageIO.write(bi, extension, outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    } 
    public static String createTimeStampStr() throws Exception {
        Calendar mycalendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss");
        String timeStamp = formatter.format(mycalendar.getTime());

        return timeStamp;
    }
}

2 个答案:

答案 0 :(得分:0)

如果你不是特别关注java代码,你可以使用一些屏幕捕获工具。 Snagit是一个很好的工具。你可以在http://www.techsmith.com/snagit.html

找到它

答案 1 :(得分:0)

尝试此示例代码,根据您的问题,它将从剪贴板复制内容并生成图像文件

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
        //Get data from clipboard and assign it to an image.
        //clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
        BufferedImage image = (BufferedImage)clipboard.getData(DataFlavor.imageFlavor);

        //file that we'll save to disk.
        File file = new File("image.jpg");

        //class to write image to disk.  You specify the image to be saved, its type,
        // and then the file in which to write the image data.
        ImageIO.write(image, "jpg", file);
    }