maven配置阿里云镜像,包比较大
一、依赖
<dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv-platform</artifactId> <version>1.5.4</version> </dependency>
二、工具类
package com.cc.demo.unit; import org.bytedeco.ffmpeg.global.avutil; import org.bytedeco.javacv.FFmpegFrameRecorder; import org.bytedeco.javacv.FrameRecorder; import org.bytedeco.javacv.Java2DFrameConverter; import org.bytedeco.ffmpeg.global.avcodec; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashMap; import java.util.Map; public class videoUtil { public static void createmp4(String outpath, String inputpath, int time) throws FrameRecorder.Exception { File folder = new File(outpath); if (!folder.exists()) { folder.mkdirs(); } //合成的MP4 String mp4SavePath = outpath + System.currentTimeMillis() + ".mp4"; int width = 1600; int height = 900; //读取所有图片 File file = new File(inputpath); File[] files = file.listFiles(); Map<Integer, File> imgMap = new HashMap<Integer, File>(); int num = 0; for (File imgFile : files) { imgMap.put(num, imgFile); num++; } create(mp4SavePath, imgMap, width, height, time); } private static void create(String mp4SavePath, Map<Integer, File> imgMap, int width, int height, int time) throws FrameRecorder.Exception, FrameRecorder.Exception { //视频宽高最好是按照常见的视频的宽高 16:9 或者 9:16 FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(mp4SavePath, width, height); //设置视频编码层模式 recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); //设置视频为25帧每秒 recorder.setFrameRate(25); //设置视频图像数据格式 recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P); recorder.setFormat("mp4"); try { recorder.start(); Java2DFrameConverter converter = new Java2DFrameConverter(); //根据文件数量定义视频时长 for (int i = 0; i < imgMap.size(); i++) { BufferedImage read = ImageIO.read(imgMap.get(i)); for (int j = 0; j < 25 * time; j++) { recorder.record(converter.getFrame(read)); } } } catch (Exception e) { e.printStackTrace(); } finally { //最后一定要结束并释放资源 recorder.stop(); recorder.release(); } } }
三、测试
package com.xx.demo; import com.xx.demo.unit.videoUtil; import org.bytedeco.javacv.FrameRecorder; import org.junit.jupiter.api.Test; class DemoApplicationTests { @Test void contextLoads() throws FrameRecorder.Exception { //输入文件目录 String img = "C:\\Users\\yjtzf\\Desktop\\file"; //输出文件目录 String mp4SavePath = "C:\\Users\\yjtzf\\Desktop\\mp4\\"; //每张图片显示时间 int time=3; videoUtil.createmp4(mp4SavePath,img,time); } }
5张图片,每张3秒,共15秒。