Java之如何截取视频第一帧

 更新时间:2023年06月19日 09:07:25   作者:上官天夜  
这篇文章主要介绍了Java之如何截取视频第一帧问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Java截取视频第一帧

方法一:使用第三方jar包截取

1、导入依赖

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

2、示例

package com.zemel.video;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
public class Test {
    /**
     * 获取指定视频的帧并保存为图片至指定目录
     * @param videofile  源视频文件路径
     * @param framefile  截取帧的图片存放路径
     * @throws Exception
     */
    public static void fetchFrame(String videofile, String framefile)
            throws Exception {
        long start = System.currentTimeMillis();
        File targetFile = new File(framefile);
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile); 
        ff.start();
        int lenght = ff.getLengthInFrames();
        int i = 0;
        Frame f = null;
        while (i < lenght) {
            // 过滤前5帧,避免出现全黑的图片,依自己情况而定
            f = ff.grabFrame();
            if ((i > 5) && (f.image != null)) {
                break;
            }
            i++;
        }
        IplImage img = f.image;
        int owidth = img.width();
        int oheight = img.height();
        // 对截取的帧进行等比例缩放
        int width = 800;
        int height = (int) (((double) width / owidth) * oheight);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
                0, 0, null);
        ImageIO.write(bi, "jpg", targetFile);
        //ff.flush();
        ff.stop();
        System.out.println(System.currentTimeMillis() - start);
    }
    public static void main(String[] args) {
        try {
            Test.fetchFrame("D:\\biudata\\vedio\\1523598768844GFE2GWDDM8.mp4", "D:\\biudata\\vedio\\test5.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法二:使用ffmpeg

1、下载ffmpeg工具(http://ffmpeg.org/)

2、代码

public static boolean processImg(String veido_path, String ffmpeg_path) {
		File file = new File(veido_path);
		if (!file.exists()) {
			System.err.println("路径[" + veido_path + "]对应的视频文件不存在!");
			return false;
		}
		List<String> commands = new java.util.ArrayList<String>();
		commands.add(ffmpeg_path);
		commands.add("-i");
		commands.add(veido_path);
		commands.add("-y");
		commands.add("-f");
		commands.add("image2");
		commands.add("-ss");
		commands.add("8");// 这个参数是设置截取视频多少秒时的画面
		// commands.add("-t");
		// commands.add("0.001");
		commands.add("-s");
		commands.add("700x525");
		commands.add(veido_path.substring(0, veido_path.lastIndexOf("."))
				.replaceFirst("vedio", "file") + ".jpg");
		try {
			ProcessBuilder builder = new ProcessBuilder();
			builder.command(commands);
			builder.start();
			System.out.println("截取成功");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	public static void main(String[] args) {
		processImg("D:\\biudata\\vedio\\15235879054813G0I1783E2.mp4",
				"F:\\开发工具\\ffmpeg.exe");
	}

Java截取视频第一帧返回InputStream,用于视频上传后作为封面

引入maven依赖

<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv-platform</artifactId>
    <version>1.4.3</version>
</dependency>

因为上面的依赖包含的jar包太多,所以我们需要排除一些东西

    <dependency>
        <groupId>org.bytedeco</groupId>
        <artifactId>javacv</artifactId>
        <version>1.4.3</version>
        <exclusions>
            <exclusion>
                <groupId>org.bytedeco</groupId>
                <artifactId>javacpp</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>flycapture</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>libdc1394</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>libfreenect</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>libfreenect2</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>librealsense</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>videoinput</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>opencv</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>tesseract</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>leptonica</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>flandmark</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>artoolkitplus</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.bytedeco</groupId>
        <artifactId>javacv-platform</artifactId>
        <version>1.4.3</version>
        <exclusions>
            <exclusion>
                <groupId>org.bytedeco</groupId>
                <artifactId>javacv</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>flycapture-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>libdc1394-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>libfreenect-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>libfreenect2-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>librealsense-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>videoinput-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>opencv-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>tesseract-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>leptonica-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>flandmark-platform</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.bytedeco.javacpp-presets</groupId>
                <artifactId>artoolkitplus-platform</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

获取视频帧返回InputStream

public class getImgUtil {
    // 获取要取得的帧数
    private static final int fifthFrame= 5;
    /**
     * @param InputStream  需要截取帧的视频的字节输入流
     *
     * @return 
     */
    public static InputStream getImg(InputStream is) {
        FFmpegFrameGrabber grabber;
        InputStream img=null ;
        try {
            grabber = new FFmpegFrameGrabber(is);
            grabber.start();
            // 视频总帧数
            int videoLength = grabber.getLengthInFrames();
            Frame frame = null;
            int i = 0;
            while (i < videoLength) {
                // 过滤前5帧,因为前5帧可能是全黑的
                frame = grabber.grabFrame();
                if ((i > fifthFrame) && (frame.image != null)) {
                    break;
                }
                i++;
            }
            Java2DFrameConverter converter = new Java2DFrameConverter();
            // 绘制图片
            BufferedImage bi = converter.getBufferedImage(frame);
            img = bufferedImageToInputStream(bi);
            grabber.stop();
            grabber.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return img;
    }
    /**
     * 将BufferedImage转换为InputStream
     * @param image
     * @return
     */
    public static InputStream bufferedImageToInputStream(BufferedImage image){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
        }
        return null;
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 在Java中使用日志框架log4j的方法

    在Java中使用日志框架log4j的方法

    Log4j有三个主要的组件/对象:Loggers(记录器),Appenders (输出源)和Layouts(布局)。这里可简单理解为日志类别,日志要输出的地方和日志以何种形式输出,今天通过本文给大家分享Java日志框架log4j的相关知识,感兴趣的朋友一起看看吧
    2021-08-08
  • Java中ReentrantLock4种常见的坑

    Java中ReentrantLock4种常见的坑

    本文主要介绍了Java中ReentrantLock 4种常见的坑,ReentrantLock默认情况下为非公平锁,下文关于其更多详情需要的小伙伴可以参考一下
    2022-05-05
  • 详解Java实现设计模式之责任链模式

    详解Java实现设计模式之责任链模式

    责任链模式是一种行为设计模式,允许你将请求沿着处理链发送,然后处理者都可对其进行处理,完成后可以再将其传递给下一个处理者。下面将会举例说明什么是责任链模式,责任链模式该如何使用
    2021-06-06
  • IDEA的Mybatis Generator驼峰配置问题

    IDEA的Mybatis Generator驼峰配置问题

    这篇文章主要介绍了IDEA的Mybatis Generator驼峰配置问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11
  • kotlin改善java代码实例分析

    kotlin改善java代码实例分析

    我们给大家整理了关于kotlin改善java代码的相关实例以及操作的详细方法,有需要的读者们参考下。
    2018-03-03
  • 如何对quartz定时任务设置结束时间

    如何对quartz定时任务设置结束时间

    这篇文章主要介绍了如何对quartz定时任务设置结束时间问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • 深入浅析jni中的java接口使用

    深入浅析jni中的java接口使用

    这篇文章主要介绍了jni中的java接口使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • 关于protected修饰符详解-源于Cloneable接口

    关于protected修饰符详解-源于Cloneable接口

    这篇文章主要介绍了protected修饰符详解-源于Cloneable接口,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • 快速解决List集合add元素,添加多个对象出现重复的问题

    快速解决List集合add元素,添加多个对象出现重复的问题

    这篇文章主要介绍了快速解决List集合add元素,添加多个对象出现重复的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • Java C++题解leetcode817链表组件示例

    Java C++题解leetcode817链表组件示例

    这篇文章主要为大家介绍了Java C++题解leetcode817链表组件示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-10-10

最新评论