首页 > 代码库 > 通过 ffmpeg 获取视频第一帧(指定时间)图片
通过 ffmpeg 获取视频第一帧(指定时间)图片
最近做一个上传教学视频的方法,上传视频的同时需要上传视频缩略图,为了避免用户上传的缩略图与视频内容不符,经理要求直接从上传的视频中截图视频的某一帧作为缩略图,并给我推荐了FFMPEG。FFMPEG 功能很强大,做视频必备的软件。
FFMPEG下载地址:https://ffmpeg.org/download.html
1、VideoThumbTaker.java 获取视频指定播放时间的图片
package video;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
/**
* 2017-08-10
* @author szq
*
*/
public class GrabberVideoThumb
{
protected String ffmpegApp;
public GrabberVideoThumb(String ffmpegApp)
{
this.ffmpegApp = ffmpegApp;
}
@SuppressWarnings("unused")
/****
* 获取指定时间内的图片
* @param videoFilename:视频路径
* @param thumbFilename:图片保存路径
* @param width:图片长
* @param height:图片宽
* @param hour:指定时
* @param min:指定分
* @param sec:指定秒
* @throws IOException
* @throws InterruptedException
*/
public void getThumb(String videoFilename, String thumbFilename, int width,
int height, int hour, int min, float sec) throws IOException,
InterruptedException
{
ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y",
"-i", videoFilename, "-vframes", "1", "-ss", hour + ":" + min
+ ":" + sec, "-f", "mjpeg", "-s", width + "*" + height,
"-an", thumbFilename);
Process process = processBuilder.start();
InputStream stderr = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
;
process.waitFor();
if(br != null)
br.close();
if(isr != null)
isr.close();
if(stderr != null)
stderr.close();
}
public static void main(String[] args)
{
GrabberVideoThumb videoThumbTaker = new GrabberVideoThumb("F:\\ffmpeg\\bin\\ffmpeg.exe");
try
{
videoThumbTaker.getThumb("f:/02-MFS介绍及特性说明_rec.mp4", "F:\\test.png", 800, 600, 0, 0, 9);
System.out.println("over");
} catch (Exception e)
{
e.printStackTrace();
}
}
}
2、GrabberVideoFirstThumb.java 获取第一帧图片
import java.io.IOException;
/***
*
* 得到第一秒(也是第一帧)图片
*/
public class GrabberVideoFirstThumb extends GrabberVideoThumb
{
public VideoFirstThumbTaker(String ffmpegApp)
{
super(ffmpegApp);
}
public void getThumb(String videoFilename, String thumbFilename, int width,
int height) throws IOException, InterruptedException
{
super.getThumb(videoFilename, thumbFilename, width, height, 0, 0, 1);
}
}
3、GrabberVideoLastThumb.java 获取最后一帧图片
/**
* 得到最后一秒(也是最后一帧)图片
*/
public class GrabberVideoLastThumb extends GrabberVideoThumb
{
public GrabberVideoLastThumb(String ffmpegApp)
{
super(ffmpegApp);
}
public void getThumb(String videoFilename, String thumbFilename, int width,
int height) throws IOException, InterruptedException
{
VideoInfo videoInfo = new VideoInfo(ffmpegApp);
videoInfo.getInfo(videoFilename);
super.getThumb(videoFilename, thumbFilename, width, height,
videoInfo.getHours(), videoInfo.getMinutes(),
videoInfo.getSeconds() - 0.2f);
}
}
参考:
http://www.codereye.com/2010/05/get-first-and-last-thumb-of-video-using.html
通过 ffmpeg 获取视频第一帧(指定时间)图片