读取视频关键帧图片

思路,用video播放视频到某一秒,之后用canvas把video画成一张图片,从而在客户端得到视频关键帧图片,实现还有一些细节处理

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style></style>
  </head>

  <body>
    <input class="input" type="file" />
    <div class="list"></div>
  </body>
  <script>

    function captureKeyFrame(file, time = 0) {
      return new Promise((resolve) => {
        const url = URL.createObjectURL(file);
        const video = document.createElement("video");
        video.width = 150;
        video.height = 200;
        video.src = url;
        video.currentTime = time;
        video.muted = true;
        video.autoplay = true;
        video.oncanplay = async function () {
          const frame = await drawVideo(video);
          resolve(frame);
        };
      });
    }

    /**
     * @description: 用canvas把video画成一张图片
     * @param {*} video
     * @return {*}{ blob: "", url: ""} blob时上传的资源,url是本地资源地址
     */
    function drawVideo(video) {
      return new Promise((resolve) => {
        const canvas = document.createElement("canvas");
        canvas.width = video.width;
        canvas.height = video.height;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        canvas.toBlob((blob) => {
          resolve({
            blob,
            url: URL.createObjectURL(blob),
          });
        });
      });
    }
  </script>
  <script>
    const input = document.querySelector(".input");
    const list = document.querySelector(".list");

    input.onchange = async function (event) {
      // 清空上一文件的关键帧图片
      list.innerHTML = "";
      const file = event.target.files[0];
      for (let i = 0; i < 10; i++) {
        const frame = await captureKeyFrame(file, i * 1);
        createPreview(frame);
      }
    };

    const createPreview = function (frame) {
      const img = new Image();
      img.src = frame.url;
      list.appendChild(img);
    };
  </script>
</html>
相关推荐
200不是二百1 分钟前
Vuex详解
前端·javascript·vue.js
滔滔不绝tao6 分钟前
自动化测试常用函数
前端·css·html5
LvManBa8 分钟前
Vue学习记录之三(ref全家桶)
javascript·vue.js·学习
码爸34 分钟前
flink doris批量sink
java·前端·flink
深情废杨杨35 分钟前
前端vue-父传子
前端·javascript·vue.js
唯创知音1 小时前
电子烟智能化创新体验:WTK6900P语音交互芯片方案,融合频谱计算、精准语音识别与流畅音频播报
人工智能·单片机·物联网·音视频·智能家居·语音识别
J不A秃V头A2 小时前
Vue3:编写一个插件(进阶)
前端·vue.js
司篂篂2 小时前
axios二次封装
前端·javascript·vue.js
姚*鸿的博客2 小时前
pinia在vue3中的使用
前端·javascript·vue.js
宇文仲竹3 小时前
edge 插件 iframe 读取
前端·edge