Vue+Video.js实现视频抽帧并返回抽帧图片Base64
作者:白野泽
这篇文章主要为大家详细介绍了Vue如何利用Video.js实现视频抽帧并返回抽帧图片Base64,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下
1.vue
// 抽帧 (url视频地址 time00:00:00:00时分秒帧 FPS视频帧率) 返回抽帧图片Base64 getImgBase64(url,time,FPS) { var base64URL = '' let video = document.createElement('video') video.setAttribute('crossOrigin', 'anonymous') //处理跨域 video.setAttribute('src', url) video.currentTime = this.timeToSeconds(time,FPS); video.addEventListener('loadeddata', function() { let canvas = document.createElement('canvas') //使用视频的宽高作为canvas、预览图的宽高 let width = video.videoWidth let height = video.videoHeight canvas.width = width canvas.height = height canvas.getContext('2d').drawImage(video, 0, 0, width, height) //绘制canvas base64URL = canvas.toDataURL('image/jpeg') //转换为base64,图片格式默认为png,这里修改为jpeg // console.log(base64URL.split(",")[1]); return base64URL.split(",")[1]; }) }, //时分秒帧 转为秒 timeToSeconds(time,FPS) { // 按小时、分钟、秒进行切割 const [hours, minutes, seconds,frame] = time.split(':'); // 计算总共的秒数 var second = parseInt(hours) * 3600 + parseInt(minutes) * 60 + parseInt(seconds)+ (1/FPS) * parseInt(frame); //若秒数为0 防止黑帧 赋值0.1 if(second == 0){ second = 0.1; } return second; },
2.Java接口测试生成文件
/** * 抽帧 * @param jsonObject * @return */ @PostMapping("/getFetchFrame") public AjaxResult getFetchFrame(@RequestBody JSONObject jsonObject) { String imgStr = jsonObject.getString("imgStr"); OutputStream out = null; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] b = decoder.decodeBuffer(imgStr); //文件存储位置 String uploadUrl = "C:\\Users\\cdv\\Desktop"; File testFile = new File(uploadUrl); if (!testFile.exists()) { testFile.mkdirs(); } String fileName = "frame" + System.currentTimeMillis() + ".jpg"; String imgFilePath = uploadUrl + "/" + fileName; out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); return AjaxResult.success(); } catch (Exception e) { logger.error("抽帧失败! error : " + e.getMessage()); return AjaxResult.error("抽帧失败"); } finally { try { if (out != null) { out.close(); } } catch (Exception e2) { logger.error("关闭输出流失败! error : " + e2.getMessage()); return AjaxResult.error("关闭输出流失败"); } } }
到此这篇关于Vue+Video.js实现视频抽帧并返回抽帧图片Base64的文章就介绍到这了,更多相关Vue Video.js视频抽帧内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!