目錄
前言
環境依賴
代碼
總結
前言
本文提供提取mp4視頻檔案的第一幀java工具類,其中包括從url下載視頻的策略,
環境依賴
Maven環境依賴
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.2</version>
</dependency>
ffmpeg環境依賴
可以參照我之前寫的去安裝部署一下:windows ffmpeg安裝部署_阿良的博客-CSDN博客
代碼
不廢話,上工具類,
package ai.guiji.csdn.tools;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import org.bytedeco.javacpp.Loader;
import java.io.IOException;
import java.util.Optional;
/** @Author huyi @Date 2021/11/11 11:08 @Description: 提取視頻第一幀 */
public class ExtractVideoFirstFrameUtil {
/**
* 提取主方法
*
* @param path MP4視頻路徑
* @param tmpDir 臨時目錄
* @return 視頻第一幀
* @throws Exception 例外
*/
public static String extract(String path, String tmpDir) throws Exception {
String mp4Path;
if (path.startsWith("http")) {
mp4Path = tmpDir + "/" + IdUtil.simpleUUID() + ".mp4";
HttpUtil.downloadFile(path, mp4Path);
} else {
mp4Path = path;
}
return ffmpegExtractImage(mp4Path, tmpDir + "/" + IdUtil.simpleUUID() + ".jpg")
.orElseThrow(() -> new Exception("提取失敗"));
}
/**
* 提取視頻第一幀圖片
*
* @param mp4Path 視頻地址
* @param picPath 圖片地址
* @return 提取的圖片地址
*/
public static Optional<String> ffmpegExtractImage(String mp4Path, String picPath) {
String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
ProcessBuilder extractBuilder =
new ProcessBuilder(
ffmpeg, "-i", mp4Path, "-f", "image2", "-ss", "1","-frames:v", "1", picPath);
try {
extractBuilder.inheritIO().start().waitFor();
} catch (InterruptedException | IOException e) {
e.printStackTrace();
return Optional.empty();
}
// 回傳圖片檔案路徑
return Optional.of(picPath);
}
}
驗證一下
public static void main(String[] args) throws Exception {
// System.out.println(extract("C:\\Users\\huyi\\Desktop\\test1.mp4",
// "C:\\Users\\huyi\\Desktop"));
System.out.println(
extract("https://xx.xx.xx.xx/test2.mp4", "C:\\Users\\huyi\\Desktop"));
}

代碼說明
1、ffmpeg的命令里面我加了一個引數 "-frames:v 1",不加雖然報錯但是圖片還是正常輸出,說明一下該引數表示輸出的圖片只有1張,如不加,報錯如下:

總結
可以按照需求調整入參,
分享
書上說,天下沒有不散之宴席,不要怕,書上還說了,人生何處不相逢,——《雪中悍刀行》
如果本文對你有用的話,請不要吝嗇你的贊,謝謝!

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/356206.html
標籤:其他
