Java截取视频文件缩略图

/**
* 截取视频第0帧的图片
*/
public static void videoImage(String filePath, String fileName,int widthdist, int heightdist) throws FrameGrabber.Exception {
File targetDir = new File(filePath + FS_FILE_APP_PATH);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath + fileName);

ff.start();
int ffLength = ff.getLengthInFrames();
org.bytedeco.javacv.Frame f;
int i = 0;
while (i < ffLength) {
f = ff.grabImage();
//截取第0帧
if(i==0){
//执行截图并放入指定位置
doExecuteFrame(f, filePath + FS_FILE_APP_PATH + fileName.substring(0,fileName.lastIndexOf(".")) + ".jpg",widthdist,heightdist);
break;
}
i++;
}
ff.stop();

}
/**
* 截取缩略图
*/
private static void doExecuteFrame(org.bytedeco.javacv.Frame f, String targerFilePath,int widthdist, int heightdist) {
String imagemat = "jpg";
if (null == f ) {
return;
}
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage bi = converter.getBufferedImage(f);
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bi, imagemat, os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
// 开始读取文件并进行压缩
Image src = ImageIO.read(is);

// 构造一个类型为预定义图像类型之一的 BufferedImage
BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);

//绘制图像 getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像
//Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

//创建文件输出流
FileOutputStream out = new FileOutputStream(targerFilePath);
//将图片按JPEG压缩,保存到out中
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
//关闭文件输出流
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

//调用
videoImage(bootdoConfig.getUploadPath()+floderPath, fileName,100,100);

//pom文件添加依赖
<!--javacv 精简版本 ffmpeg -->
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>1.3.1</version>
<exclusions>
<exclusion>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg</artifactId>
<version>3.2.1-1.3</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg</artifactId>
<version>3.2.1-1.3</version>
<classifier>windows-x86_64</classifier>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg</artifactId>
<version>3.2.1-1.3</version>
<classifier>linux-x86_64</classifier>
</dependency>
posted @ 2018-12-28 13:55  liw66  阅读(1514)  评论(0编辑  收藏  举报