视频生成缩略图


文章目录


视频生成缩略图

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

使用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 "";
    }

参考文献

相关推荐
Honmaple13 分钟前
2026 年做短视频,这 5 个 AI 技能插件我把每个都跑通了
后端
j_xxx404_19 分钟前
用系统调用从零封装一个C语言标准I/O库 | 附源码
linux·c语言·开发语言·后端
覆东流21 分钟前
第4天:Python输入与输出
后端·python·photoshop·输入与输出
倒霉蛋小马1 小时前
SpringBoot3中配置Knife4j
java·spring boot·后端
我叫黑大帅1 小时前
从零实现一个完整 RAG 系统:基于 Eino 框架的检索增强生成实战
后端·面试·go
NotFound4861 小时前
实战分享怎样实现Spring Boot 中基于 WebClient 的 SSE 流式接口操作
java·spring boot·后端
码事漫谈9 小时前
大模型输出的“隐性结构塌缩”问题及对策
前端·后端
小江的记录本10 小时前
【网络安全】《网络安全常见攻击与防御》(附:《六大攻击核心特性横向对比表》)
java·网络·人工智能·后端·python·安全·web安全
努力的小雨10 小时前
龙虾量化实战法(QClaw)
后端
橙露10 小时前
SpringBoot 整合 MinIO:分布式文件存储上传下载
spring boot·分布式·后端