How do I solve problems in my screenshot-taking ap

2019-07-09 02:41发布

I wrote a GUI-based Java program that takes 25 screenshots per second and saves them at a user-defined location.
It works pretty well except that it has two problems:

  • The mouse cursor is missing from the images and I know it will be because BufferedImages do not contain cursor information in them. They have to be added programatically.

  • The thread that takes screenshots is a daemon thread. So if I close the application, the thread is killed and the PNG image that was being written gets corrupted. I want to avoid that.

  • Here are the images of my application:
    The award-winning, intuitive GUI:
    enter image description here

    The high-definition images captured look like this:
    enter image description here
    As you can see from the image the cursor information is being displayed in the console using MouseInfo's static methods.


    Please let me know how to solve the above mentioned two problems.
    After solving the problem, the images now look like this:
    with cursor

    标签: java image io
    1条回答
    霸刀☆藐视天下
    2楼-- · 2019-07-09 03:14

    The mouse cursor is missing from the images and I know it will be because BufferedImages do not contain cursor information in them. They have to be added programatically.

    That is correct, you have to add the cursor afterwards. The reason for this is that a screenshot taken with the Robot class never contains the cursor. Not really because "the BufferedImage doesn't contain mouse info". A BufferedImage is a class that contains a raster of pixels.

    The thread that takes screenshots is a daemon thread. So if I close the application, the thread is killed and the PNG image that was being written gets corrupted. I want to avoid that.

    Simply, in the screenshot thread, use a flag that indicates wether it should continue or not. Keep taking screenshots as long as that boolean is set to true. Make sure to make it non-deamon. So, when you close the application, set the flag to false. Probably the most easy way to do this is to add a WindowListener:

    yourFrame.addWindowListener(new WindowAdapter()
    {
        public void windowClosed(WindowEvent e)
        {
            screenshotThread.stopTakingScreenshots(); // This methods set the flag
        }
    }
    

    Also notice that you are not taking the time it takes to make and save a screenshot in count. You use a fixed sleep of 40 milliseconds, but let's say that it takes 4 milliseconds to take and save the screenshot, then you should sleep for only 36 milliseconds. To time how long it takes to make the screenshot, use System.currentTimeMillis(); before and after your takeShot() method and make the difference.

    查看更多
    登录 后发表回答