赞
踩
1. 获取图片前,首先我们需要引入相关maven依赖
- <dependency>
- <groupId>org.bytedeco</groupId>
- <artifactId>ffmpeg</artifactId>
- <version>6.0-1.5.9</version>
- </dependency>
- <dependency>
- <groupId>org.bytedeco</groupId>
- <artifactId>javacv-platform</artifactId>
- <version>1.5.9</version>
- </dependency>
如依赖无法正常引入时,可通过百度寻找该jar并加入本地仓库中(jar引入方式见:本地Maven仓库导入外部jar)
2. 创建java工具类ExtractFlvFirstFrame.java获取图片
- import lombok.extern.slf4j.Slf4j;
- import org.bytedeco.javacv.FFmpegFrameGrabber;
- import org.bytedeco.javacv.Frame;
- import org.bytedeco.javacv.FrameGrabber;
- import org.bytedeco.javacv.Java2DFrameConverter;
-
- import javax.imageio.ImageIO;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
-
- @Slf4j
- public class ExtractFlvFirstFrame {
-
- /**
- * 获取指定帧数的封面图片
- *
- * @param filePath flv地址(eg:http://ip:port/xxx.flv)
- */
- private static BufferedImage getBufferedImageByFrame(String filePath) throws IOException {
- FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(filePath);
- return getBufferedImageByFrame(grabber);
- }
-
- private static BufferedImage getBufferedImageByFrame(FFmpegFrameGrabber grabber) throws FrameGrabber.Exception {
- grabber.start();
- Frame frame;
- frame = grabber.grabImage();
- Java2DFrameConverter converter = new Java2DFrameConverter();
- BufferedImage buffer = converter.getBufferedImage(frame);
- grabber.stop();
- return buffer;
- }
-
- /**
- * @param flvPath
- * @param imgPath 文件存储全路径
- * @throws Exception
- */
- public static File getFlvImg(String flvPath, String imgPath) {
- try {
- bufferedImageToByteArray(getBufferedImageByFrame(flvPath), imgPath);
- return new File(imgPath);
- } catch (IOException e) {
- e.printStackTrace();
- log.error("通过视频流地址“" + flvPath + "”生成图片“" + imgPath + "”失败");
- }
- return null;
- }
-
- /**
- * 将BufferedImage转换为byte[]
- *
- * @param image
- * @param imgPath 文件存储全路径
- * @return
- */
- private static void bufferedImageToByteArray(BufferedImage image, String imgPath) throws IOException {
- ImageIO.write(image, "jpg", new File(imgPath));
- }
-
- }
调用方法getFlvImg即可获得直播视频流的其实帧图,其实入参flvPath为直播的flv地址全路径,imgPath为要保存的图片的全路径(含拓展名,eg: C:/aaa/123.jpg)
注意:
jar版本请勿随意使用,另外需要注意的是该方式虽然能获取首帧的图片,但是项目打包后会非常的大。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。