參考了眾多網(wǎng)友的代碼墙杯,改良后可以取任何一幀的圖片
安裝依賴
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.3</version>
</dependency>
代碼實(shí)現(xiàn)
/**
* 獲取指定幀數(shù)的封面圖片
*
* @param frameNum 幀數(shù)
* @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");
}