java如何获取视频第一帧封面图片?

背景:

视频第一帧就是在视频中提取第一帧的图片画面,在视频处理中,截帧可以用于视频预览、封面生成、缩略图制作等多种应用场景。以下是一个简化的步骤,描述如何使用FFmpeg来获取视频的第一帧。

1.添加依赖
首先,你需要将FFmpeg和相关的依赖项添加到你的项目中。如果你使用Maven,可以在pom.xml中添加以下依赖【本来就一个依赖的,但是那个依赖太大,所以就从中过滤了一些无效依赖】

        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacv</artifactId>
            <version>1.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacpp</artifactId>
            <version>1.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>opencv</artifactId>
            <classifier>windows-x86_64</classifier>
            <version>4.5.3-1.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>opencv</artifactId>
            <classifier>linux-x86_64</classifier>
            <version>4.5.3-1.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>openblas</artifactId>
            <classifier>windows-x86_64</classifier>
            <version>0.3.17-1.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>openblas</artifactId>
            <classifier>linux-x86_64</classifier>
            <version>0.3.17-1.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>ffmpeg</artifactId>
            <classifier>windows-x86_64</classifier>
            <version>4.4-1.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>ffmpeg</artifactId>
            <classifier>linux-x86_64</classifier>
            <version>4.4-1.5.6</version>
        </dependency>

  2.代码案例:       

 将第一帧的图片以流的形式,上传到OBS,最后返回OBS的图片url给到前端

/**
     * 截取视频第一帧图片【解决图片旋转问题】
     * @param videoUrl
     * @return
     */
    public String getFirstFrameOfVideo(String videoUrl) throws Exception {
        if (StringUtils.isBlank(videoUrl)){
            throw new Exception("上传视频地址为空!");
        }
        try {
            URL url = new URL(videoUrl);
            URLConnection con = url.openConnection();
            if (enable) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
                con = url.openConnection(proxy);
            }
            con.connect();
            InputStream is = con.getInputStream();
            FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(is);
            frameGrabber.start();
            int length = frameGrabber.getLengthInFrames();
            log.info("============> length:{}", length);
            int i = 0;
            Frame f = null;
            while (i < length) {
                // 过滤前5帧,避免出现全黑的图片
                f = frameGrabber.grabFrame();
                if ((i > 5) && (f.image != null)) {
                    break;
                }
                i++;
            }
            log.info("============> f:{}", f == null ? "为null" : "不为null");
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage bufferedImage = converter.getBufferedImage(f);
            String rotate = frameGrabber.getVideoMetadata("rotate");
            if (StringUtils.isNotEmpty(rotate)) {
                bufferedImage = rotate(bufferedImage, Integer.parseInt(rotate));
            }
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            String coverImgPath = obsPublicUpload(input,  DateUtil.format(DateUtil.date(), "yyyy/MM/dd"), "videoImg-" + DateUtil.format(DateUtil.date(), "HHmmssSSS") + IdUtil.simpleUUID() + ".jpg");
            frameGrabber.stop();
            os.close();
            is.close();
            return coverImgPath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static BufferedImage rotate(BufferedImage src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        int type = src.getColorModel().getTransparency();
        Rectangle rect_des = calcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
        BufferedImage bi = new BufferedImage(rect_des.width, rect_des.height, type);
        Graphics2D g2 = bi.createGraphics();
        g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
        g2.drawImage(src, 0, 0, null);
        g2.dispose();
        return bi;
    }

    public static Rectangle calcRotatedSize(Rectangle src, int angel) {
        if (angel >= 90) {
            if(angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }
        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);
        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new java.awt.Rectangle(new Dimension(des_width, des_height));
    }

    /**
     * 上传封面图片
     * @param inputStream
     * @param dirName
     * @param fileName
     * @return
     */
    public String obsPublicUpload(InputStream inputStream, String dirName, String fileName){
        log.info("===================> 开始将视频封面上传obs");
        ObsConfiguration oc = new ObsConfiguration();
        if (enable) {
            oc.setHttpProxy(host, port, null, null);
        }
        oc.setEndPoint(obsSignUtil.getEndPoint());
        String path = obsSignUtil.getPublicPrefix()+dirName+"/"+fileName;
        try (ObsClient obsClient = new ObsClient(obsSignUtil.getAk(), obsSignUtil.getSk(), oc)) {
            log.info("视频第一帧封面地址为:"+path);
            // 声明上传请求对象
            PutObjectRequest request = new PutObjectRequest();
            // 设置桶名
            request.setBucketName(obsSignUtil.getBucketName());
            // 设置上传路径
            request.setObjectKey(path);
            // 上传文件
            request.setInput(inputStream);
            // 设置对象访问权限为公共读
            request.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
            obsClient.putObject(request);
            String resultUrl = obsSignUtil.getObsPrefix() + path;
            log.info("=======================> 上传obs响应url地址:{}", resultUrl);
            return resultUrl;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取视频第一画面,你可以使用`MediaMetadataRetriever`类。下面是一个使用`ExtractVideoInfoUtil`工具类来获取视频第一画面的示例代码: ```java import android.graphics.Bitmap; import android.media.MediaMetadataRetriever; import android.os.Bundle; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); String videoPath = "your_video_path"; // 替换成你的视频文件路径 Bitmap firstFrame = ExtractVideoInfoUtil.extractFrame(videoPath); if (firstFrame != null) { imageView.setImageBitmap(firstFrame); } } } public class ExtractVideoInfoUtil { public static Bitmap extractFrame(String videoPath) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setDataSource(videoPath); return retriever.getFrameAtTime(); } catch (Exception e) { e.printStackTrace(); } finally { retriever.release(); } return null; } } ``` 在上述代码中,你需要将`videoPath`替换为你的视频文件路径。`ExtractVideoInfoUtil`类中的`extractFrame`方法会使用`MediaMetadataRetriever`类来获取视频第一画面,并返回一个`Bitmap`对象。然后,你可以将这个`Bitmap`对象设置给一个`ImageView`来显示第一画面。 请注意,这段代码仅获取视频第一画面,并没有进行异步处理。在实际应用中,你可能需要在后台线程中执行这个操作,并添加适当的错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值