java-FFmpeg1.4.4读取视频随机截图

package per.qy.dexter.video;
 
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
 
import javax.imageio.ImageIO;
 
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.junit.Test;
 
public class FFmpegTest {
 
    @Test
    public void splitVideo() {
        FFmpegFrameGrabber frameGrabber = null;
        try {
            frameGrabber = FFmpegFrameGrabber.createDefault("d:/111.mp4");
            frameGrabber.start();
            long frameTime = frameGrabber.getLengthInTime() / 1000000;
            int frameLength = frameGrabber.getLengthInFrames();
            List list = random(frameTime, frameLength);
            for (int i = 0; i < frameLength; i++) {
                Frame frame = frameGrabber.grabImage();
                if (list.contains(i)) {
                    Java2DFrameConverter converter = new Java2DFrameConverter();
                    BufferedImage image = converter.getBufferedImage(frame);
                    FileOutputStream outFile = null;
                    try {
                        outFile = new FileOutputStream(
                                "d:/111/" + UUID.randomUUID().toString().replaceAll("-", "") + ".png");
                        ImageIO.write(image, "png", outFile);
                    } catch (IOException e) {
                    } finally {
                        try {
                            if (outFile != null) {
                                outFile.close();
                            }
                        } catch (IOException e) {
                        }
                    }
                }
            }
            System.out.println(String.format("视频总时长=%ss,总帧数=%s,抽取帧数=%s", frameTime, frameLength, list.size()));
        } catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
        } finally {
            if (frameGrabber != null) {
                try {
                    frameGrabber.stop();
                } catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
                }
            }
        }
    }
 
    private List random(long frameTime, int frameLength) {
        long count = 200;
        if (frameTime <= 100) {
            count = 10;
        } else if (frameTime <= 1800) {
            count = frameTime / 10;
        }
        List list = new ArrayList();
 
        if (frameLength < count) {
            for (int i = 0; i < frameLength; i++) {
                list.add(i);
            }
            return list;
        }
 
        long range = (frameLength - 5) / count;
        for (long i = range + 5; i < frameLength; i = i + range) {
            int rand = (int) ((i - range) + Math.random() * range);
            list.add(rand);
        }
        return list;
    }
 
}

你可能感兴趣的:(java-FFmpeg1.4.4读取视频随机截图)