I'm writing a screen capture module in Java, but I'm having serious performance issues writing screenshots to disk. What else can I do?

StackOverflow https://stackoverflow.com/questions/1087891

Question

I'm writing a screen capture module using the Robot class. I'm taking screenshots of the application every x milliseconds and writing them to disk. After screen capture is finished, I'm compiling the screenshots to video with FFMPEG.

However, writing images to disk is extremely slow and grinds my application to a halt. What am I missing? Is there a better way to write a simple screen capture module?

Edit: I've tried several ways of writing the images to disk, and all are very slow. I've been sticking with the following, due to its ease of use:

ImageIO.write(bufferedImage ,"jpg", file);
Was it helpful?

Solution

Or encode the image into video format right when you capture the image, and avoid writing the large temporary file at all. Full code using Xuggler can be found here:

Xuggler Screen Capture Demo Code

OTHER TIPS

Try putting your write into a new thread so you do not have to wait for slow disk IO.

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.schedule(new Runnable(){
    @Override
     public void run() {
            writeImageHere(bufferedImage, file);
     }                  
}

Just watch out for concurrency issues.

The second (memory intensive) solution is to buffer your jpgs and keep them all in memory and write only when a certain amount of time has passed or your program exits.

The default buffered image is quite big. Try having it as a smaller format and then write it down.

I've used .png before and it's small enough.

Post a bit more code and will see what other thing may be wrong in yours.

EDIT

I use this:

        BufferedImage bufferedImage  = new BufferedImage(
                                              widthFromRobot, 
                                              heightFromRobot,
                                              BufferedImage.    TYPE_3BYTE_BGR );

        bufferedImage.getGraphics().drawImage( fromRobotScreenCapture, 0,0, null );

       // get a file name 
       ImageIO.write( bufferedImage, "png", someFile  );

Create a new image with the same width and height but a different image types.

Write the image in that new image, and save that new image to disk.

Explore the different image type values and see which is better for you. Of course there could be a tradeoff between quality and speed. ( I think however your problem is somewhere else but try this first )

Check out reply 6 of this posting. It implies that using JAI will improve write performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top