温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js如何实现GIF动图分解成多帧图片上传

发布时间:2021-04-19 11:31:06 来源:亿速云 阅读:329 作者:小新 栏目:web开发

小编给大家分享一下js如何实现GIF动图分解成多帧图片上传,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

分解gif图片需要使用libgif-js这个库!

1. 引入Git库

import SuperGif from './libgif.js'

2. 分解Gif为png图片

const GifDecomposer = {
  structureGifObject (gifFiles, cb) { // gifFiles 获取的文件对象 e.target.files[0]
    const gifImg = document.createElement('img');
    gifImg.setAttribute('rel:animated_src', URL.createObjectURL(gifFiles));
    gifImg.setAttribute('rel:auto_play', '0');
    // Modified pictures must be added to the body
    document.body.appendChild(gifImg);
    // Construction example
    var rub = new SuperGif({ gif: gifImg });
    rub.load(() => {
      var img_list = [];
      for (let i=1; i <= rub.get_length(); i++) {
        // Traversing through each frame of a GIF instance
        rub.move_to(i);
        // Converting each frame of canvas into a file object
        let cur_file = this.convertCanvasToImage(rub.get_canvas(), gifFiles.name.replace('.gif', '') + `-${i}`)
        img_list.push({
          file_name: cur_file.name,
          url: URL.createObjectURL(cur_file),
          file: cur_file,
        })
      }
      cb(img_list)
    });
  },
  dataURLtoFile (dataurl, filename) {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    var n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
  },
  convertCanvasToImage (canvas, filename) {
    return this.dataURLtoFile(canvas.toDataURL('image/png'), filename);
  }
}

3. 上传每一张图片

/**
 * costume upload GIF decomposer
 */
 const filesImg = function (list, storage, costumeFormat, assetType, handleCostume) {
  let proDataList = list.map((item, index) => {
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        reader.readAsArrayBuffer(item.file);
        reader.onload = () => {
          let data = {result: reader.result, type: item.file.type, name: item.file.name}
          resolve(data);
        };
        reader.onerror = (error) => {reject(error)};
      })
    })
  Promise.all(proDataList).then(res => {
    res.forEach(item => {
    // 上传
    })
  }).catch(data => {console.log(data)})
 }

以上是“js如何实现GIF动图分解成多帧图片上传”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI