java利用FFMpeg将mp4转换为gif

本文介绍了一种使用ffmpeg工具将MP4视频文件转换为GIF动画的方法。通过设置不同的参数可以控制转换的时间段及输出文件的长度。示例代码展示了如何在Java中调用ffmpeg实现这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上和官方资料整合
存在问题,在不丢帧的情况下转换后的gif会比原始mp4文件大很多。

package jinx;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 利用ffmpeg将mp4转换为gif
 */
public class FFMpegUtil {

    //Windows下 ffmpeg.exe的路径
    //private static String ffmpegEXE = "D:\\Downloads\\ffmpeg-20180528-ebf85d3-win64-static\\bin\\ffmpeg.exe";

    //Linux与mac下  ffmpeg的路径
    private static String ffmpegEXE = "/usr/local/Cellar/ffmpeg/4.1.2/bin/ffmpeg";


    /**
     *
     * @param time       截取视频长度
     * @param start      截取开始时间 如果为null表示全部转换为gif
     * @param inputPath  被转换的mp4文件位置
     * @param outPath    转换后gif文件位置
     * @throws Exception
     */
    public static void convetor(int time,String start,String inputPath, String outPath) throws Exception {
        List<String> command = new ArrayList<String>();
        command.add(ffmpegEXE);
        if(0!=time){
            command.add("-t");
            command.add(String.valueOf(time));
        }
        if(start!=null&&!"00:00:00".equals(start)){
            command.add("-ss");
            command.add(start);
        }
        command.add("-i");
        command.add(inputPath);
        command.add(outPath);
        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = null;
        try {
            process = builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //使用这种方式会在瞬间大量消耗CPU和内存等系统资源,所以这里我们需要对流进行处理
        InputStream errorStream = process.getErrorStream();
        InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
        BufferedReader br = new BufferedReader(inputStreamReader);

        String line = "";
        while ((line = br.readLine()) != null) {
        }
        if (br != null) {
            br.close();
        }
        if (inputStreamReader != null) {
            inputStreamReader.close();
        }
        if (errorStream != null) {
            errorStream.close();
        }

    }


 public static void main(String[] args) {
    String videoInputPath = "/Users/jinx/Downloads/1.mp4";
    String coverOutputPath = "/Users/jinx/Downloads/4.gif";
    try {
        convetor(5,"00:00:01",videoInputPath,coverOutputPath);
    } catch (Exception e) {
       e.printStackTrace();
    }
 }

}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值