视频生成缩略图


文章目录


视频生成缩略图

最近有个需求,视频上传之后在列表和详情页需要展示缩略图

使用ffmpeg

首先引入jar包

xml 复制代码
<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacpp</artifactId>
    <version>1.4.3</version>
</dependency>
<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv</artifactId>
    <version>1.4.3</version>
</dependency>
<dependency>
    <groupId>org.bytedeco.javacpp-presets</groupId>
    <artifactId>ffmpeg-platform</artifactId>
    <version>4.0.2-1.4.3</version>
</dependency>

代码如下

java 复制代码
public String getThumbnails(String videoFilePath){
        String path = "/Users/zhanghe/Desktop/pic/";
        String fileName =  videoFilePath.substring(videoFilePath.lastIndexOf("/") + 1, videoFilePath.lastIndexOf("."))+"_thumb.jpg";

        String filePath = StringUtils.join(path, fileName);
        File targetFile = new File(filePath);
        try {
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFilePath);
            ff.start();
            // 视频总帧数
            int videoLength = ff.getLengthInFrames();

            org.bytedeco.javacv.Frame f  = null;
            int i = 0;
            while (i < videoLength) {
                // 过滤前20帧,因为前20帧可能是全黑的
                // 这里看需求,也可以直接根据帧数取图片
                f = ff.grabFrame();
                if (i > 20 && f.image != null) {
                    break;
                }
                i++;
            }
            int owidth = f.imageWidth;
            int oheight = f.imageHeight;
            // 对截取的帧进行等比例缩放
            int width = 800;
            int height = (int) (((double) width / owidth) * oheight);
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage fecthedImage = converter.getBufferedImage(f);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);
            ImageIO.write(bi, "jpg", targetFile);
            ff.stop();

            System.out.println(targetFile.getPath());
          return targetFile.getPath();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

参考文献

相关推荐
copyer_xyf20 小时前
Python 异常处理
前端·后端·python
llz_11221 小时前
web-第三次课后作业
前端·后端·web
MageGojo1 天前
天气 API 接入实战:基于 ApiZero 实现实时天气、分钟级降水和 15 天预报查询
java·后端·spring·api 接口接入·接口实战
pe7er1 天前
软件设计不要“既要又要”
前端·后端·架构
柏舟飞流1 天前
Spring Boot 深入实践指南:从入门到工程化落地
spring boot·后端·firefox
IT_陈寒1 天前
Java Stream并行流的坑:我花了3小时才找到的线程安全问题
前端·人工智能·后端
橘子海全栈攻城狮1 天前
【最新源码】鸟博士微信小程序 023
spring boot·后端·web安全·微信小程序·小程序
Hiter_John1 天前
Golang的运算符
开发语言·后端·golang
皮皮林5511 天前
Dubbo 的 SPI 和 JDK 的 SPI 有什么区别?
后端
金銀銅鐵1 天前
用 Tkinter 实现一个罗马数字转整数的简单工具
后端·python