Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take a screenshot of desktop fast with Java in Windows (ffmpeg, etc.)?

I would like to use java to take a screenshot of my machine using FFMPEG or some other solution. I know linux works with ffmpeg without JNI, but running it in Windows does not work and may require (JNI?) is there any sample of some simple Java class (and anything else necessary) to capture a screenshot runnable in a windows environment? Is there some alternative to FFMPEG? I want to take screenshot at a rate faster than the Java Robot API, which I have found to work at taking screenshots, but is slower than I would like.

I know in Linux this works very fast:

import com.googlecode.javacv.*;

public class ScreenGrabber {
    public static void main(String[] args) throws Exception {
        int x = 0, y = 0, w = 1024, h = 768;
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(":0.0+" + x + "," + y);
        grabber.setFormat("x11grab");
        grabber.setImageWidth(w);
        grabber.setImageHeight(h);
        grabber.start();

        CanvasFrame frame = new CanvasFrame("Screen Capture");
        while (frame.isVisible()) {
            frame.showImage(grabber.grab());
        }
        frame.dispose();
        grabber.stop();
    }

This does not work in windows environment. Am not sure if there is some way I could use this same code, but use javacpp to actually get it working without having to change much of the above code.

Goal is to take screenshots of screen fast, but then stop after it takes a screenshot that is "different", aka. screen changed because of some event like, a window is window closed, etc.

like image 988
Setsuna Avatar asked Jul 10 '14 04:07

Setsuna


1 Answers

According to the official ffmpeg documentation you should be able to keep it pretty cross platform if you make the file parameter passed to the FFmpegFrameGrabber (which is really an input parameter that gets passed down as the -i option to ffmpeg) adhere to the different formats each device expects.

ie:

for Windows: dshow expects -i video="screen-capture-recorder"

for OSX: avfoundation expects -i "<screen device index>":

and for Linux: x11grab expects -i :<display id>+<x>,<y>.

So just passing those values (arguments to -i) to the constructor and setting the format (via setFormat) accordingly should do the trick.

like image 51
Roberto Andrade Avatar answered Oct 20 '22 00:10

Roberto Andrade