Clue Mediator

How to convert a GIF to Video in Node.js

📅August 22, 2022

In this article, we will show you how to convert a GIF to Video in Node.js. Here, we’ll show you the simple way to generate a video from animated GIF using NPM package.

Package Version

@ffmpeg-installer/ffmpeg

^1.1.0

@ffprobe-installer/ffprobe

^1.4.1

fluent-ffmpeg

^2.1.2

File Structure

  • generate-gif-nodejs

    • images

      • result.gif
    • node_modules

    • output

      • result.mp4
    • package-lock.json

    • package.json

    • README.md

    • server.js

Steps to convert a video from gif

  1. Setup Node project
  2. Install NPM dependencies
  3. API to convert a video from gif
  4. Output

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.

Create REST API in Node.js

2. Install NPM dependencies

To generate a video, we need to install the @ffmpeg-installer/ffmpeg, @ffprobe-installer/ffprobe and fluent-ffmpeg NPM packages to project. Run the following command to install the dependencies.

npm i @ffmpeg-installer/ffmpeg @ffprobe-installer/ffprobe fluent-ffmpeg

3. API to convert a video from gif

Here, we will get the GIF image from the directory called `images` and generate a mp4 video in `output` directory. You can refer the file structure for more understanding.

Now, check the following API code to convert a GIF to video.

const ffmpegInstaller = require("@ffmpeg-installer/ffmpeg");
const ffprobe = require("@ffprobe-installer/ffprobe");

const ffmpeg = require("fluent-ffmpeg")()
  .setFfprobePath(ffprobe.path)
  .setFfmpegPath(ffmpegInstaller.path);

app.get('/gif-to-video', (req, res) => {
  ffmpeg
    .input('./images/result.gif')
    .noAudio()
    .outputOptions('-pix_fmt yuv420p')
    .output(`./output/result.mp4`)
    .on("end", () => {
      res.send({ message: 'Video Generated!' });
    })
    .on("error", (e) => console.log(e))
    .run();
});

In the above code, we have initialize the `fluent-ffmpeg` and set the path. You can add audio during conversion.

4. Output

Open the `output` directory after running the project API. You'll see that the created mp4 video is available.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Demo & Source Code

GitHub Repository