1. 程式人生 > 其它 >java FFmpeg 圖片生成視訊

java FFmpeg 圖片生成視訊

POM

如果版本有問題,就參考這個:http://bytedeco.org/download/

<!--  ffmpeg  -->
    <dependency>
      <groupId>org.bytedeco</groupId>
      <artifactId>javacpp-platform</artifactId>
      <version>1.5.5</version>
    </dependency>
    <dependency>
      <groupId>org.bytedeco</groupId>
      <artifactId>opencv-platform</artifactId>
      <version>4.5.1-1.5.5</version>
    </dependency>
    <dependency>
      <groupId>org.bytedeco</groupId>
      <artifactId>ffmpeg-platform</artifactId>
      <version>4.3.2-1.5.5</version>
    </dependency>
    <dependency>
      <groupId>org.bytedeco</groupId>
      <artifactId>opencv-platform-gpu</artifactId>
      <version>4.5.1-1.5.5</version>
    </dependency>
    <dependency>
      <groupId>org.bytedeco</groupId>
      <artifactId>javacv-platform</artifactId>
      <version>1.5.5</version>
    </dependency>

方法:

public static void pic2MovByFfmpeg(String mp4SavePath,String picturesPath, int width, int height) throws FFmpegFrameRecorder.Exception {
        //視訊寬高最好是按照常見的視訊的寬高  16:9  或者 9:16
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(mp4SavePath, width, height);
        //設定視訊編碼層模式
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
        
//設定視訊為1幀每秒 recorder.setFrameRate(1); //設定視訊影象資料格式 recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P); recorder.setFormat("mp4"); File file = new File(picturesPath); File[] flist = file.listFiles(); try { recorder.start(); Java2DFrameConverter converter
= new Java2DFrameConverter(); //錄製一個22秒的視訊 for (int i = 0; i < flist.length; i++) { BufferedImage read = ImageIO.read(flist[i]); recorder.record(converter.getFrame(read),avutil.AV_PIX_FMT_RGB32_1); } } catch (Exception e) { e.printStackTrace(); } finally { //最後一定要結束並釋放資源 recorder.stop(); recorder.release(); } }

測試:

@Test
    public void pic2movByFfmpeg() throws Exception {
        String picPath="C:\\Users\\Tyler\\Postman\\files";
        String videoPath="C:\\Users\\Tyler\\Downloads\\test.mp4";
        FileHelper.pic2MovByFfmpeg(videoPath,picPath,640,480);
    }