截取指定时间的那一帧作为视频封面

将一下代码用cv大法扔到这里即可运行

<!DOCTYPE html> 
<html> 
<body> 

<video width="400" controls>
  <source src="/html/mov_bbb.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

<p>These are the frames' images generated by getVideoImage():</p>
<ol id="olFrames"></ol>

<script type="text/JavaScript">
function getVideoImage(path, secs, callback) {
  var me = this, video = document.createElement('video');
  video.onloadedmetadata = function() {
    if ('function' === typeof secs) {
      secs = secs(this.duration);
    }
    this.currentTime = Math.min(Math.max(0, (secs < 0 ? this.duration : 0) + secs), this.duration);
  };
  video.onseeked = function(e) {
    var canvas = document.createElement('canvas');
    canvas.height = video.videoHeight;
    canvas.width = video.videoWidth;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    var img = new Image();
    img.src = canvas.toDataURL();
    callback.call(me, img, this.currentTime, e);
  };
  video.onerror = function(e) {
    callback.call(me, undefined, undefined, e);
  };
  video.src = path;
}

function showImageAt(secs) {
  var duration;
  getVideoImage(
    '/html/mov_bbb.mp4',
    function(totalTime) {
      duration = totalTime;
      return secs;
    },
    function(img, secs, event) {
      if (event.type == 'seeked') {
        var li = document.createElement('li');
        li.innerHTML += '<b>Frame at second ' + secs + ':</b><br />';
        li.appendChild(img);
        document.getElementById('olFrames').appendChild(li);
        if (duration >= ++secs) {
          showImageAt(secs);
        };
      }
    }
  );
}
showImageAt(0);
</script>

<p>
Video courtesy of 
<a href="https://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.
</p>
</body> 
</html>

  此功能可以按原样使用,也可以修改。重要的是要注意,视频与网页必须位于完全相同的域中,否则由于画布被污染,此代码将不起作用。

  参考文章:https://cwestblog.com/2017/05/03/javascript-snippet-get-video-frame-as-an-image/

posted @ 2021-09-10 10:48  Tang_Qin  阅读(229)  评论(0)    收藏  举报