ffmpeg 修改視頻封面


千金縱買相如賦,脈脈此情誰訴。

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/java/java37.jpg

概述

有時候我們希望使用某一張圖片作為視頻素材的封面 ,而不是素材中的某幀。今天使用ffmpeg批量替換視頻素材封面。

環境裝備

官網下載安裝 ffmpeg

准備素材

准備好視頻素材和封面圖片

編寫程序

package cn.merryyou.file;

import java.io.*;

/**
 * 修改視頻封面
 * Created by i@merryyou.cn on 2020/3/24
 *
 * @VERSION 1.0
 */
public class ChangeVedioCover {

    public static final String FFMPEG_PATH = "D:/ffmpeg/bin/ffmpeg.exe"; // ffmpeg 程序迷路
    public static final String FILE_PATH = "E:/BaiduNetdiskDownload/測試"; //需要替換封面的視頻目錄
    public static final String IMAGE_PATH = "E:/BaiduNetdiskDownload/測試/1.png"; // 需要替換的封面照片
    public static final String COMMAND = "%s -i %s -i %s -map 1 -map 0 -c copy -disposition:0 attached_pic -y %s"; // ffmpeg 替換封面的命令

    public static void main(String[] args) throws Exception {
        printPath(new File(FILE_PATH));
    }

    public static void printPath(File file) throws IOException {
        File[] files = file.listFiles();
        for (File a : files) {
            System.out.println(a.getAbsolutePath());
            if (a.getAbsolutePath().endsWith(".mp4")) {
                String newPath = a.getParent() + "/" + a.getName().substring(0, a.getName().lastIndexOf(".")) + "_.mp4"; // 新生成的文件名后面添加_ 下划線
                String cmd = String.format(COMMAND, FFMPEG_PATH, a.getAbsolutePath(), IMAGE_PATH, newPath);
                execCmd(cmd);
                a.delete();// 刪除源文件
            }
            if (a.isDirectory()) {
                printPath(a);
            }
        }
    }

    public static void execCmd(String cmd) {
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/C", cmd);
        Process process = null;
        try {
            process = builder.redirectErrorStream(true).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream in = process.getInputStream();
        outStream(in);
    }

    private static void outStream(InputStream in) {
        // 用一個讀輸出流類去讀
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line;
        // 逐行讀取輸出到控制台
        try {
            while ((line = br.readLine()) != null) {
//                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

效果如下

修改封面前

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/java/java38.png

修改封面后

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/java/java39.png

總結

更多ffmpeg 命令參考鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM