此例子可用于:视频内截取某一帧作为封面图(可指定时间)、需要视频内某张图用作表情包。。。

前提:本文是在windows下测试可用,linux还未尝试

          需提前准备好第三方软件ffmpeg,

      且被操作的视频必须为ffmpeg支持的视频格式(ffmpeg支持大部分主流格式)

          参考:https://www.cnblogs.com/interdrp/p/6509802.html

可直接复制尝试使用,当然路径要改成自己的

(注释配合main方法里的调用,应该能看懂)

package com.founder.util.video;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class VideoUtil {

    public static void main(String[] args) {
        try {
            getImgFromVideo("D:\\ffmpeg\\ffmpeg2016\\bin\\ffmpeg.exe", "d:\\ys\\StoryBrooke.mp4", "d:\\ys\\lain.jpg", 204, 140, 0, 0, 26);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取指定时间内的图片
     * @param ffmpegPath (ffmpeg路径)
     * @param videoPath (视频路径)
     * @param imgPath (图片存放路径)
     * @param width (图片宽度)
     * @param height (图片高度)
     * 以下为需要指定的时间
     * @param hour
     * @param min
     * @param sec
     * @return
     */
    public static boolean getImgFromVideo(String ffmpegPath, String videoPath, String imgPath, int width,
            int height, int hour, int min, float sec) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(ffmpegPath, "-y",
                    "-i", videoPath, "-vframes", "1", "-ss", hour + ":" + min
                            + ":" + sec, "-f", "mjpeg", "-s", width + "*" + height,
                    "-an", imgPath);

            Process process = processBuilder.start();
            InputStream stderr = process.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            while ((br.readLine()) != null);
            process.waitFor();
            if (br != null)
                br.close();
            if (isr != null)
                isr.close();
            if (stderr != null)
                stderr.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}

 

posted on 2018-03-08 11:54  乔砂  阅读(906)  评论(0编辑  收藏  举报