1. 程式人生 > >java使用ffmpeg擷取視訊某個時間點的截圖

java使用ffmpeg擷取視訊某個時間點的截圖

1.軟體安裝

 

  • mac

brew install ffmpeg

安裝後路徑:"/usr/local/Cellar/ffmpeg/4.0.1/bin

ffmpeg –version 檢視版本

 

  • linux

暫缺,後補

  • windwos

   下載地址:

   https://ffmpeg.zeranoe.com/builds/

解壓即可

配置path環境變數

ffmpeg –version 檢視版本

 

2.具體的java類

//獲取視訊相關資訊

package com.cmcc.core.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 獲取視訊的資訊 FFMPEG homepage http://ffmpeg.org/about.html
 */
public class VideoInfo {
    // 視訊路徑
    private String ffmpegApp;
    // 視訊時a
    private int hours;
    // 視訊分
    private int minutes;
    // 視訊秒
    private float seconds;
    // 視訊width
    private int width;
    // 視訊height
    private int heigt;

    public VideoInfo() {
    }

    public VideoInfo(String ffmpegApp) {
        this.ffmpegApp = ffmpegApp;
    }

    public String toString() {
        return "time: " + hours + ":" + minutes + ":" + seconds + ", width = " + width + ", height= " + heigt;
    }

    public void getInfo(String videoFilename) throws IOException, InterruptedException {
        String tmpFile = videoFilename + ".tmp.png";
        ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y", "-i", videoFilename, "-vframes", "1", "-ss", "0:0:0", "-an", "-vcodec", "png", "-f", "rawvideo", "-s", "100*100", tmpFile);

        Process process = processBuilder.start();

        InputStream stderr = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stderr);
        BufferedReader br = new BufferedReader(isr);
        String line;
        // 列印 sb,獲取更多資訊。 如 bitrate、width、heigt
        StringBuffer sb = new StringBuffer();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        new File(tmpFile).delete();

        System.out.println("video info:\n" + sb);
        Pattern pattern = Pattern.compile("Duration: (.*?),");
        Matcher matcher = pattern.matcher(sb);

        if (matcher.find()) {
            String time = matcher.group(1);
            calcTime(time);
        }

        pattern = Pattern.compile("w:\\d+ h:\\d+");
        matcher = pattern.matcher(sb);

        if (matcher.find()) {
            String wh = matcher.group();
            // w:100 h:100
            String[] strs = wh.split("\\s+");
            if (strs != null && strs.length == 2) {
                width = Integer.parseInt(strs[0].split(":")[1]);
                heigt = Integer.parseInt(strs[1].split(":")[1]);
            }
        }

        process.waitFor();
        if (br != null)
            br.close();
        if (isr != null)
            isr.close();
        if (stderr != null)
            stderr.close();
    }

    private void calcTime(String timeStr) {
        String[] parts = timeStr.split(":");
        hours = Integer.parseInt(parts[0]);
        minutes = Integer.parseInt(parts[1]);
        seconds = Float.parseFloat(parts[2]);
    }

    public String getFfmpegApp() {
        return ffmpegApp;
    }

    public void setFfmpegApp(String ffmpegApp) {
        this.ffmpegApp = ffmpegApp;
    }

    public int getHours() {
        return hours;
    }

    public void setHours(int hours) {
        this.hours = hours;
    }

    public int getMinutes() {
        return minutes;
    }

    public void setMinutes(int minutes) {
        this.minutes = minutes;
    }

    public float getSeconds() {
        return seconds;
    }

    public void setSeconds(float seconds) {
        this.seconds = seconds;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeigt() {
        return heigt;
    }

    public void setHeigt(int heigt) {
        this.heigt = heigt;
    }

    public static void main(String[] args) {
        VideoInfo videoInfo = new VideoInfo("D:\\hbk\\ffmpeg-20170718-012620a-win64-static\\bin\\ffmpeg.exe");
        try {
            videoInfo.getInfo("D:\\hbk\\hbk.mp4");
            System.out.println(videoInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
	
//擷取視訊幾時幾分幾秒的圖片


	package com.cmcc.core.Util;
	
	import java.io.BufferedReader;
	import java.io.IOException;
	import java.io.InputStream;
	import java.io.InputStreamReader;
	
	public class VideoThumbTaker {
	    protected String ffmpegApp;
	
	    public VideoThumbTaker(String ffmpegApp) {
	        this.ffmpegApp = ffmpegApp;
	    }
	
	    @SuppressWarnings("unused")
	    /****
	    * 獲取指定時間內的圖片
	    * @param videoFilename:視訊路徑
	    * @param thumbFilename:圖片儲存路徑
	    * @param width:圖片長
	    * @param height:圖片寬
	    * @param hour:指定時
	    * @param min:指定分
	    * @param sec:指定秒
	    * @throws IOException
	    * @throws InterruptedException
	    */
	    public void getThumb(String videoFilename, String thumbFilename, int width, int height, int hour, int min, float sec) throws IOException, InterruptedException {
	        ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y", "-i", videoFilename, "-vframes", "1", "-ss", hour + ":" + min + ":" + sec, "-f", "mjpeg", "-s", width + "*" + height,
	                "-an", thumbFilename);
	
	        Process process = processBuilder.start();
	
	        InputStream stderr = process.getErrorStream();
	        InputStreamReader isr = new InputStreamReader(stderr);
	        BufferedReader br = new BufferedReader(isr);
	        String line;
	        while ((line = br.readLine()) != null)
	            ;
	        process.waitFor();
	
	        if (br != null)
	            br.close();
	        if (isr != null)
	            isr.close();
	        if (stderr != null)
	            stderr.close();
	    }
	
	    public static void main(String[] args) {
	        VideoThumbTaker videoThumbTaker = new VideoThumbTaker("/usr/local/Cellar/ffmpeg/4.0.1/bin/ffmpeg");
	        try {
	            videoThumbTaker.getThumb("/yidong/work_day/11/1106/aa.avi", "/yidong/work_day/11/1106/aa.png", 800, 600, 0, 1, 5);
	            System.out.println("over");
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	}


//封裝工具類,擷取中間時間的視訊截圖

package com.cmcc.core.Util;

import java.io.IOException;
/**
 * 視訊、圖片工具類
 * @author lvyangfan
 *
 */
public class VideoUtils {

	public static void main(String[] args) {
	
		
		try {
			getCenterImg("/usr/local/Cellar/ffmpeg/4.0.1/bin/ffmpeg","/yidong/work_day/11/1106/aa.avi","/yidong/work_day/11/1106/aa.png");
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
	}
	/**
	* 獲取視訊中間時間點的截圖
	* @param ffmpegPath 本地ffmpeg工具位置
	* @param videoPath 視訊位置
	* @param imgPath 生成圖片位置
	* @throws IOException
	* @throws InterruptedException
	*/
	public static void getCenterImg(String ffmpegPath,String videoPath,String imgPath) throws IOException, InterruptedException {

		VideoInfo videoInfo = new VideoInfo(ffmpegPath);
		videoInfo.getInfo(videoPath);
		System.out.println(videoInfo);
		int hours = videoInfo.getHours();
		int minutes = videoInfo.getMinutes();
		float seconds = videoInfo.getSeconds();
		float total = hours * 3600 + minutes * 60 + seconds;
		total = total / 2;

		hours = (int) (total / 3600);
		minutes = (int) ((total % 3600) / 60);
		seconds = total - hours * 3600 - minutes * 60;
		
	    VideoThumbTaker videoThumbTaker = new VideoThumbTaker(ffmpegPath);
		videoThumbTaker.getThumb(videoPath, imgPath, 800, 600, hours, minutes, seconds);
         System.out.println("over");

	}

}