I am trying to resize an animated gif using NodeJS. I need it to stay animated after resizing.
My app is currently using Sharp to resize other images, but it appears to not support exporting animated gifs.
If possible I would like to find an npm package that doesn't rely on another external software like *Magick. It would be awesome if it supported streams as well.
I don't know about any native npm package, but you can use gifsicle.
Gifsicle is a command-line tool for creating, editing, and getting information about GIF images and animations.
This is a good article about resizing animated gifs using gifsicle: https://davidwalsh.name/resize-animated-gif
Example 1: I used gifsicle
module to install the gifsicle's binary file:
const { execFile } = require('child_process');
const gifsicle = require('gifsicle');
console.time('execute time');
// You can use these options for resizing:
// --scale 0.5
// --resize-fit-width 300
// --resize-fit-height 200
// --resize 300x200
execFile(gifsicle, ['--resize-fit-width', '300', '-o', 'output.gif', 'input.gif'], err => {
console.timeEnd('execute time');
if (err) {
throw err;
}
console.log('image resized!');
});
Example 2: Use the spawn
method to get a readable stream:
const fs = require('fs');
const { spawn } = require('child_process');
const gifsicle = require('gifsicle');
console.time('execute time');
const stream = spawn(gifsicle, ['--resize-fit-width', '300', 'input.gif']);
stream.on('close', () => {
console.timeEnd('execute time');
console.log('image resized!');
});
stream.stdout.pipe(fs.createWriteStream('output.gif'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With