总结js获取视频第一帧作为封面图并且上传的解决方法
html代码
1 2 3 4 5 6 7 8 9 10 11 12 13
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head>
<body> <video src="http://localhost:8080/test.mp4" id="tmpVideo"></video> <img src="" alt="" id="tmpImg"> </body> </html>
|
js代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| function DrawCanvas(videoId) { var tmpVideo = document.getElementById(videoId); try { var canvasEle = document.createElement("canvas"); canvasEle.width = tmpVideo.offsetWidth; canvasEle.height = tmpVideo.offsetHeight; canvasEle.getContext('2d').drawImage(tmpVideo, 0, 0, canvasEle.width, canvasEle.height); var imgUrl = canvasEle.toDataURL("image/jpeg"); var filename = `${videoId}.jpg` var binary = atob(imgUrl.split(',')[1]); var mime = imgUrl.split(',')[0].match(/:(.*?);/)[1]; var array = []; for (var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], { type: mime, }) } catch (e) { console.log(e) return false } }
function getVideoPoster(url) { return new Promise((resolve, reject) => { var videoEle = document.createElement('video') var videoId = `${(new Date().getTime()).toString() + (Math.ceil(Math.random() * 1000).toString())}` videoEle.width = 600 videoEle.id = `poster-${videoId}` videoEle.style.cssText = 'opacity:0;position:fixed;left:0;top:0;z-index: -1;' videoEle.setAttribute('src', url) videoEle.setAttribute("crossOrigin", 'Anonymous') videoEle.onloadedmetadata = function () { setTimeout(() => { var res = DrawCanvas(`poster-${videoId}`, `video-block${videoId}`) if (res) { resolve(res) } else { reject(false) } document.body.removeChild(videoEle); }, 300) } document.body.appendChild(videoEle); }) }
|
最后更新时间: