How can I get a frame sample (jpeg) from a video (mov)

I know that the original question is solved, nevertheless, I am posting this answer in case anyone else got stuck like I did.

Since yesterday, I have tried everything, and I mean everything to do this. All available Java libraries are either out of date, not maintained anymore or lack any kind of usable documentation (seriously??!?!)

I tried JFM (old and useless), JCodec (no documentation whatsoever), JJMpeg (looks promising but is very difficult and cumbersome to use due to lack of Java-class documentation), OpenCV auto-Java builds and a few bunch of other libraries that I cannot remember.

Finally, I decided to take a look at JavaCV‘s (Github link) classes and voila! It contains FFMPEG bindings with detailed documentations.

<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv</artifactId>
    <version>1.0</version>
</dependency>

Turns out there is a very easy way to extract video frames from a video file to a BufferedImage and by extension a JPEG file. The class FFmpegFrameGrabber could be easily used for grabbing individual frames and converting them to BufferedImage. A code sample is as follows:

FFmpegFrameGrabber g = new FFmpegFrameGrabber("textures/video/anim.mp4");
g.start();

Java2DFrameConverter converter = new Java2DFrameConverter();

for (int i = 0 ; i < 50 ; i++) {
    
    Frame frame = g.grabImage(); // It is important to use grabImage() to get a frame that can be turned into a BufferedImage

    BufferedImage bi = converter.convert(frame);

    ImageIO.write(bi, "png", new File("frame-dump/video-frame-" + System.currentTimeMillis() + ".png"));
}

g.stop();

Basically, this code dumps the first 50 frames of the video and saves them as a PNG file. The good thing is that the internal seek function, works on actual frames not keyframes (a problem that I had with JCodec)

You can refer to the JavaCV’s homepage to find out more about other classes that can be used for capturing frames from WebCams etc. Hope this answer helps 🙂

Leave a Comment