javacv-ffmpeg (two) picture capture

Description

Support local files, rtmp, rtsp, http-flv, hls

1. Video pull

The demonstration method only cuts one picture. If you want to cut several pictures every few seconds, add time to the if condition.
f.timestamp can get the frame time in microseconds.

		//方法或者外部类代码在后边
		FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
		// 微秒 大概为设置时间的两倍 
		ff.setOption(TimeoutOption.RW_TIMEOUT.getKey(), "10000000");
		// rtsp 默认udp 丢包 改为tcp
		ff.setOption("rtsp_transport", "tcp");
		ff.start();
		Frame f = null;
		while (true) {
    
    
			f = ff.grabFrame();
			if (null != f) {
    
    
				// 若显示帧不为关键帧,则寻找相邻的下一帧
				if (f.image != null) {
    
    
					doExecuteBase(f, timestamp);
					break;
				}
			}
		}

		ff.release();
		ff.stop();

二、TimeoutOption

/**
 * 流媒体超时没有通用选项。每个协议都有 自己的选项列表。
 */
public enum TimeoutOption {
    
    

	/**
	 * 取决于协议(FTP,HTTP,RTMP,SMB,SSH,TCP,UDP或UNIX)。
	 * 
	 * http://ffmpeg.org/ffmpeg-all.html
	 */
	TIMEOUT,
	/**
	 * 协议
	 *
	 * 等待(网络)读/写操作完成的最长时间, 以微秒为单位。
	 *
	 * http://ffmpeg.org/ffmpeg-all.html#Protocols
	 */
	RW_TIMEOUT,
	/**
	 * Protocols -> RTSP
	 *
	 * 设置套接字TCP I / O超时(以微秒为单位)。
	 *
	 * http://ffmpeg.org/ffmpeg-all.html#rtsp
	 */
	STIMEOUT;

	public String getKey() {
    
    
		return toString().toLowerCase();
	}

}

Three, output as base64

	/**
	 * 输出成base64,保存到数据结构
	 */
	public static void doExecuteBase(Frame f, String filename, long date) {
    
    
		if (null == f || null == f.image) {
    
    
			return;
		}

		Java2DFrameConverter converter = new Java2DFrameConverter();
		BufferedImage bi = converter.getBufferedImage(f);

		String base64 = getImageBinary(bi, "jpg");
	}

	/**
	 * 图片流转化成base64
	 */
	public static String getImageBinary(BufferedImage bi, String format) {
    
    
		try {
    
    
			ByteArrayOutputStream baos = new ByteArrayOutputStream();// io流
			ImageIO.write(bi, format, baos);// 写入流中
			byte[] bytes = baos.toByteArray();// 转换成字节
			BASE64Encoder encoder = new BASE64Encoder();
			String base64 = encoder.encodeBuffer(bytes).trim();// 转换成base64串
			base64 = base64.replaceAll("\n", "").replaceAll("\r", "");// 删除 \r\n
			return base64;
		} catch (IOException e) {
    
    
			log.info("base64转化失败");
			e.printStackTrace();
		}
		return null;
	}

Fourth, output cost-local pictures

	/**
	 * 输出成本地图片
	 */
	public static void doExecuteFrame(Frame f, String targetFileName) {
    
    
		if (null == f || null == f.image) {
    
    
			return;
		}
		Java2DFrameConverter converter = new Java2DFrameConverter();
		BufferedImage bi = converter.getBufferedImage(f);
		File output = new File(targetFileName);
		try {
    
    
			ImageIO.write(bi, "jpg", output);

		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
	}

Guess you like

Origin blog.csdn.net/u013947963/article/details/103410420