Generate a GIF from Images in Node.js
In this article, we will show you how to generate a GIF from Images in Node.js. Here, we’ll show you the simple way to generate animated GIF from images using `gifencoder` and `canvas` NPM packages.
Package Version
gifencoder
^2.0.1
canvas
^2.9.3
File Structure
-
generate-gif-nodejs
-
images
- img1.jpg
- img2.jpg
- img3.jpg
- img4.jpg
- img5.jpg
-
node_modules
-
output
- result.gif
-
package-lock.json
-
package.json
-
README.md
-
server.js
-
Steps to generate a GIF from images
1. Setup Node project
To create a REST API in Node.js, we’ll use the express framework. If you don’t know how to design a REST API in Node.js using the express framework, please checkout the link below.
2. Install NPM dependencies
To generate a GIF animation image, we need to install the gifencoder and canvas NPM packages to project. Run the following command to install the dependencies.
npm i gifencoder canvas
3. API to generate a GIF from images
Here, we will get the list of images from the directory called `images` and generate a GIF image in `output` directory. You can refer the file structure for more understanding.
Now, check the following API code to generate a GIF from images.
const fs = require('fs');
const GIFEncoder = require('gifencoder');
const { createCanvas, loadImage } = require('canvas');
const width = 400;
const height = 400;
app.get('/generate-gif', (req, res) => {
const canvas = createCanvas(width, height);
const ctx = canvas.getContext('2d');
const encoder = new GIFEncoder(width, height);
encoder.createReadStream().pipe(fs.createWriteStream('./output/result.gif'));
encoder.start();
encoder.setRepeat(0);
encoder.setDelay(1000);
encoder.setQuality(10);
const imgList = fs.readdirSync('./images/');
imgList.forEach(async (f, i) => {
const image = await loadImage(`./images/${f}`);
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
encoder.addFrame(ctx);
if (i === imgList.length - 1) {
encoder.finish();
res.send({ message: 'GIF Generated!' });
}
});
});
In the above code, we have initialize the `gifencoder` and load the images in `canvas` to generate the GIF image.
4. Output
Open the `output` directory after running the project API. You'll see that the created GIF picture is available.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂