Search code examples
filepond

Make FilePond Image Transform plugin ignore (animated) GIFs


I'm using FilePond with an image editor, so I also load the Image Transform plugin.

However, when a user uploads a GIF file, I want the outputted image to remain a GIF file. Currently it's transformed to a PNG by the Image Transform plugin.

Is there a way to make FilePond disable the Image Transform plugin when a GIF file is uploaded, or somehow change the output mime-type?


Solution

  • Please install version 3.6.0 of the image transform plugin and use the function below to filter out animated GIF images.

    Animated GIF filter code snippet from Is it possible to detect animated gif images client side?

    FilePond.create({
        imageTransformImageFilter: (file) => new Promise(resolve => {
    
            // no gif mimetype, do transform
            if (!/image\/gif/.test(file.type)) return resolve(true);
    
            const reader = new FileReader();
            reader.onload = () => {
    
                var arr = new Uint8Array(reader.result),
                i, len, length = arr.length, frames = 0;
    
                // make sure it's a gif (GIF8)
                if (arr[0] !== 0x47 || arr[1] !== 0x49 || 
                    arr[2] !== 0x46 || arr[3] !== 0x38) {
                    // it's not a gif, we can safely transform it
                    resolve(true);
                    return;
                }
    
                for (i=0, len = length - 9; i < len, frames < 2; ++i) {
                    if (arr[i] === 0x00 && arr[i+1] === 0x21 &&
                        arr[i+2] === 0xF9 && arr[i+3] === 0x04 &&
                        arr[i+8] === 0x00 && 
                        (arr[i+9] === 0x2C || arr[i+9] === 0x21)) {
                        frames++;
                    }
                }
    
                // if frame count > 1, it's animated, don't transform
                if (frames > 1) {
                    return resolve(false);
                }
    
                // do transform
                resolve(true);
            }
            reader.readAsArrayBuffer(file);
    
        })
    });