javacv 视频增加视频(画中画)
1、项目添加依赖
<dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv-platform</artifactId> <version>1.5</version> </dependency>
2、准备两段视频
public static void main(String[] args) { System.out.println("视频合并"); String sourceFilePath="/Users/dongxr/Desktop/test.mp4"; String mergeFielPath="/Users/dongxr/Desktop/test2.mp4"; File file=new File(sourceFilePath); //抓取资源 FFmpegFrameGrabber frameGrabber1 = new FFmpegFrameGrabber(sourceFilePath); //待处理的视频文件 FFmpegFrameGrabber frameGrabber2 = new FFmpegFrameGrabber(mergeFielPath); // Frame frame = null; Frame mergeFrame = null; FFmpegFrameRecorder recorder = null; String fileName = null; try{ //开始抓取 frameGrabber1.start(); frameGrabber2.start(); //随机数 Random random=new Random(); fileName = file.getAbsolutePath() + random.nextInt(100)+".mp4"; System.out.println("--文件名-->>"+fileName); recorder = new FFmpegFrameRecorder(fileName, frameGrabber1.getImageWidth(), frameGrabber1.getImageHeight(), frameGrabber1.getAudioChannels()); // recorder.setFormat("mp4"); recorder.setSampleRate(frameGrabber1.getSampleRate()); recorder.setFrameRate(frameGrabber1.getFrameRate()); recorder.setTimestamp(frameGrabber1.getTimestamp()); recorder.setVideoBitrate(frameGrabber1.getVideoBitrate()); recorder.setVideoCodec(frameGrabber1.getVideoCodec()); recorder.start(); int index=0; while (true){ frame=frameGrabber1.grabFrame(); if(frame ==null){ break; } // System.out.println("音频=="+(frame.samples ==null)+"视频=="+ (frame.image==null)); //帧图片 if(frame.image !=null){ IplImage iplImage = Java2DFrameUtils.toIplImage(frame); BufferedImage buffImg=Java2DFrameUtils.toBufferedImage(iplImage); //图片绘制 mergeFrame=frameGrabber2.grabFrame(); if(mergeFrame !=null){ System.out.println("--合并视频--"+(mergeFrame.image ==null)); //判断获取图片帧是否为空,如果为空就在获取一帧,循环判断 while (mergeFrame.image ==null){ mergeFrame=frameGrabber2.grabFrame(); } Graphics2D graphics = buffImg.createGraphics(); Image mergeBuffer = Java2DFrameUtils.toBufferedImage(mergeFrame); graphics.drawImage(mergeBuffer,0,100,200,150,null); graphics.dispose(); } //新的一帧 Frame newFrame = Java2DFrameUtils.toFrame(buffImg); recorder.record(newFrame); } //设置音频 if(frame.samples !=null){ recorder.recordSamples(frame.sampleRate,frame.audioChannels,frame.samples); } System.out.println("帧值="+index); index ++; } recorder.stop(); recorder.release(); frameGrabber2.stop(); frameGrabber1.stop(); }catch (Exception e){ e.printStackTrace(); } }
3、引入文件
import org.bytedeco.javacv.FFmpegFrameGrabber; import org.bytedeco.javacv.FFmpegFrameRecorder; import org.bytedeco.javacv.Frame; import org.bytedeco.javacv.Java2DFrameUtils; import org.bytedeco.opencv.opencv_core.IplImage; import java.awt.*; import java.awt.image.BufferedImage;
备注:嵌入的画面自己可以根据坐标随意摆放
原文地址:https://blog.csdn.net/weixin_37852133/article/details/115891140