yaogengzhu / daily-share

个人博客记录、内容在issues
30 stars 4 forks source link

抽取视频第一帧上传作为背景 (2024-05-10) #207

Open yaogengzhu opened 6 months ago

yaogengzhu commented 6 months ago

背景: 动态壁纸 mp4 预览加载卡顿。在前端层面抽取视频第一帧作为视频背景图。

前端实现方案:

const upload = async (file) => {
  const video = document.createElement('video');
  video.src = URL.createObjectURL(file);
  await video.play(); // 等待视频加载
  // 创建一个 canvas 元素
  const canvas = document.createElement('canvas');
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  // 将视频的第一帧绘制到 canvas 上
  const context = canvas.getContext('2d');
  context.drawImage(video, 0, 0, canvas.width, canvas.height);

  // 将 canvas 转换为 Blob 对象
  const frameBlob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg'));
  const frameFile = new File([frameBlob], "frame.jpg", { type: 'image/jpeg' });
  const formData = new FormData();
  formData.append("file", file);
  formData.append("frame", frameFile);
  console.log(formData, "formData");
 // 请求逻辑
};