Java程序将视频转化为动图

1、引入依赖

<!-- https://mvnrepository.com/artifact/org.bytedeco/javacv-platform -->
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacv-platform</artifactId>
            <version>1.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.madgag/animated-gif-lib -->
        <dependency>
            <groupId>com.madgag</groupId>
            <artifactId>animated-gif-lib</artifactId>
            <version>1.4</version>
        </dependency>

注意,这里引入的javacv依赖是全平台的,会比较重量级。如果只想在某一个或多个平台使用,只引入对应平台的模块即可,这里请参考官方说明:

地址: or

2、使用案例

这里是将某一个目录下的MP4文件生成同名的gif文件demo代码,仅供参考。

package javacv;

import com.madgag.gif.fmsware.AnimatedGifEncoder;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.io.File;
import java.io.FileOutputStream;

public class Test {

    public static void main(String[] args) {
        // 将指定目录的 MP4 文件生成同名的 gif 文件
        File videoDir = new File("/Users/mozat-gz/Downloads");
        for (File file : videoDir.listFiles()) {
            String videoPath = file.getPath();
            if (videoPath.endsWith(".mp4")) {
                String gifPath = videoPath.substring(0, videoPath.lastIndexOf(".")) + ".gif";
                try {
                    video2Gif(videoPath, gifPath);
                } catch (Exception e) {
                    System.out.println("文件 [" + videoPath + "] 处理异常!");
                    e.printStackTrace();
                }
            }
        }
    }

    private static void video2Gif(String videoPath, String gifPath) throws Exception {
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath);
             FileOutputStream targetFile = new FileOutputStream(gifPath)) {
            grabber.start();
            int frames = grabber.getLengthInFrames();
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.setFrameRate(frames);
            encoder.start(targetFile);
            Java2DFrameConverter converter = new Java2DFrameConverter();
            for (int i = 0 ; i < frames ; i += 8) {// 8帧合成1帧?(反正越大动图越小、越快)
                encoder.setDelay((int) grabber.getDelayedTime());
                encoder.addFrame(converter.convert(grabber.grabImage()));
                grabber.setFrameNumber(i);
            }
            encoder.finish();
        }
    }
}
经验分享 程序员 微信小程序 职场和发展