SoFunction
Updated on 2025-03-10

JS implements GIF animation decomposition into multi-frame image upload

When you encounter a project, you need to support uploading gif images and display the decomposed frame images to the user at one time. Just go to the code without saying much

Decompose gif images need to be usedlibgif-jsThis library!

1. Introduce Git library

import SuperGif from './'

2. Decompose Gif into png images

const GifDecomposer = {
  structureGifObject (gifFiles, cb) { // The file object obtained by gifFiles [0]    const gifImg = ('img');
    ('rel:animated_src', (gifFiles));
    ('rel:auto_play', '0');
    // Modified pictures must be added to the body
    (gifImg);
    // Construction example
    var rub = new SuperGif({ gif: gifImg });
    (() => {
      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 = (rub.get_canvas(), ('.gif', '') + `-${i}`)
        img_list.push({
          file_name: cur_file.name,
          url: (cur_file),
          file: cur_file,
        })
      }
      cb(img_list)
    });
  },
  dataURLtoFile (dataurl, filename) {
    const arr = (',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    var n = ;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = (n);
    }
    return new File([u8arr], filename, {type:mime});
  },
  convertCanvasToImage (canvas, filename) {
    return (('image/png'), filename);
  }
}

3. Upload each picture

/**
 * costume upload GIF decomposer
 */
 const filesImg = function (list, storage, costumeFormat, assetType, handleCostume) {
  let proDataList = ((item, index) => {
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        ();
         = () => {
          let data = {result: , type: , name: }
          resolve(data);
        };
         = (error) => {reject(error)};
      })
    })
  (proDataList).then(res => {
    (item => {
    // Upload    })
  }).catch(data => {(data)})
 }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.