vue使用gitshot生成gif

vue使用gitshot生成gif

问题背景

本文将介绍vue中使用gitshot生成gif。

问题分析

解决思路:

使用input组件上传一个视频,获取视频文件后用一个video组件进行播放,播放过程进行截图生成图片数组。
demo演示上传一个视频,然后生成对应的gif。

注意事项:

html中使用video标签调用本地视频结果只有音频没有视频画面问题?
解决思路:
html中 video 标签支持的视频格式,一共支持三种格式: Ogg、MPEG4、WebM。但这三种格式对于浏览器的兼容性却各不同。
比如MP4格式,MP4只是一个容器,里面还有一个叫编码器的东西。格式虽然都是MP4但是html中只支持H.264的编码格式。所以要用软件来转码。
MP4 = MPEG 4文件使用 H264 视频编解码器和AAC音频编解码器
WebM = WebM 文件使用 VP8 视频编解码器和 Vorbis 音频编解码器
Ogg = Ogg 文件使用 Theora 视频编解码器和 Vorbis音频编解码器。
可使用格式工厂软件对本地视频格式进行处理。

问题解决

(1)安装所需的npm包

npm install gifshot --save

(2)完整代码如下:

<template>
  <div style="display: flex; flex-direction: column;">
    <!-- 选择要上传的视频 -->
    <div style="display: flex;">
      <input type="file" ref="videoInput" accept="video/mp4" style="margin: 15px;">
      <button @click="handleFileChange" style="height: 30px; width: 50px; margin: 15px;">确定</button>
    </div>

    <video style="width: 400px;height: 400px; margin: 15px;" ref="videoRef" :src="videoUrl" controls>
    </video>
    <div style="margin: 15px;">输出gif如下:</div>
  </div>
</template>
 
<script>
import gifshot from 'gifshot';
export default {
  data() {
    return {
      videoUrl: null,
      interval: null,
      clipImgs: [],
      delay: 200,
    }
  },
  methods: {
    handleFileChange() {
      // 获取选择的视频文件
      this.selectedVideo = this.$refs.videoInput.files[0];
      console.log(this.selectedVideo);

      if (!this.selectedVideo) {
        console.log('请选择文件');
        return;
      }
      this.videoUrl = '';
      this.convertFileToBase64(this.selectedVideo)
        .then(base64Data => {
          this.videoUrl = base64Data;
          console.log('this videoUrl', this.videoUrl);
          this.start() //视频截图并转成gif
        })
        .catch(error => {
          console.error('Error:', error);
        });
    },

    // 文件转成base64
    convertFileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
      });
    },
    // base64转image
    getImageFromBase64(base64Image) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = base64Image;
        img.onload = () => resolve(img);
        img.onerror = reject;
      });
    },

    start() {
      console.log('start');
      // 每次开始重置以下值
      clearInterval(this.interval);

      let video = this.$refs.videoRef; //获取video元素
      console.log('start', video);
      video.addEventListener('canplay', function () {
        console.log('canplay', video);
        video.play();
      });
      let that = this;

      video.addEventListener('play', function () {
        var canvas = document.createElement('canvas');

        // 根据视频大小调整画布尺寸
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        console.log('play', video);

        // 获取上下文对象
        var context = canvas.getContext('2d');

        this.interval = setInterval(() => {
          context.drawImage(video, 0, 0);  // 将视频内容绘制到画布上
          let screenshotDataURL = canvas.toDataURL(); // 转成Base64
          console.log(screenshotDataURL, that.clipImgs);
          that.clipImgs.push(screenshotDataURL) //把所有截图放到一个数组里
        }, that.delay)
      });
      // 监听视频播放结束后,说明截图完成。定时器停止,清除定时器缓存,开始转换。
      video.addEventListener('ended', function (e) {
        console.log('stop');
        clearInterval(this.interval)
        this.interval = null
        that.makeGIF()
      })
    },

    async makeGIF() {
      // 使用gifshot,将图片数组转成gif
      gifshot.createGIF({
        gifWidth: 200,
        gifHeight: 200,
        images: this.clipImgs,
        interval: 0.1,
        numFrames: 10,
        frameDuration: 1,
        fontWeight: 'normal',
        fontSize: '16px',
        fontFamily: 'sans-serif',
        fontColor: '#ffffff',
        textAlign: 'center',
        textBaseline: 'bottom',
        sampleInterval: 10,
        numWorkers: 2
      }, function (obj) {
        console.log(obj, " obj");
        if (!obj.error) {
          let image = obj.image;
          let animatedImage = document.createElement('img');
          animatedImage.src = image;
          animatedImage.style = 'margin: 15px';
          document.body.appendChild(animatedImage);
        }
      });
    }
  }
}
</script>

运行结果如下:
在这里插入图片描述

选择本地视频文件,确定选择会播放该视频,播放完成生成对应的gif文件。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值