视频生成缩略图


文章目录


视频生成缩略图

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

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

参考文献

相关推荐
派大鑫wink5 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势
java·spring boot·后端
程序员爱钓鱼6 小时前
Node.js 编程实战:文件读写操作
前端·后端·node.js
xUxIAOrUIII6 小时前
【Spring Boot】控制器Controller方法
java·spring boot·后端
Dolphin_Home6 小时前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)
java·spring boot·后端·spring cloud·database·广度优先·图搜索算法
zfj3216 小时前
go为什么设计成源码依赖,而不是二进制依赖
开发语言·后端·golang
weixin_462446236 小时前
使用 Go 实现 SSE 流式推送 + 打字机效果(模拟 Coze Chat)
开发语言·后端·golang
JIngJaneIL6 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
小信啊啊7 小时前
Go语言切片slice
开发语言·后端·golang
Victor3568 小时前
Netty(20)如何实现基于Netty的WebSocket服务器?
后端
缘不易8 小时前
Springboot 整合JustAuth实现gitee授权登录
spring boot·后端·gitee