参考了众多网友的代码,改良后可以取任何一帧的图片
安装依赖
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.3</version>
</dependency>
代码实现
/**
* 获取指定帧数的封面图片
*
* @param frameNum 帧数
* @param filePath 文件所在路径
*/
public static BufferedImage getBufferedImageByFrame(int frameNum, String filePath) throws IOException {
FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(filePath);
return getBufferedImageByFrame(frameNum, grabber);
}
private static BufferedImage getBufferedImageByFrame(int frameNum, FFmpegFrameGrabber grabber)
throws FrameGrabber.Exception {
grabber.start();
Frame frame;
int i = 0;
int fps = (int)grabber.getFrameRate();
BufferedImage buffer = null;
while (i < grabber.getLengthInFrames()) {
frame = grabber.grabImage();
if (i >= fps && i % (fps * frameNum) == 0) {
Java2DFrameConverter converter = new Java2DFrameConverter();
buffer = converter.getBufferedImage(frame);
break;
}
i++;
}
grabber.stop();
return buffer;
}
@Test
public void test() throws IOException {
String filePath = path + "15895090168002467.mov";
BufferedImage buffer = getBufferedImageByFrame(1, filePath);
saveImage(buffer, "158950901680024671.jpg", "jpg");
}