Converting GIF to MP4

rafi993

Rafi

Posted on November 15, 2020

Converting GIF to MP4

GIF's are awesome we use them everywhere. But the issue with GIF's are they are usually much larger in size compared to their video counterparts.

To overcome this we usually convert GIF to MP4 and play them in loop. Usually we do this conversion in the server using ffmpeg or wrapper over ffmpeg. This conversion might be resource intensive.

Luckily there is WASM port of ffmpeg. Which means we could use it to convert GIF to MP4 easily as follow

import FFmpeg from '@ffmpeg/ffmpeg';
import { even } from 'prelude-ls';

const { createFFmpeg, fetchFile } = FFmpeg;

const ffmpeg = createFFmpeg({ log: true });

document
  .getElementById('fileInput')
  .addEventListener('change', async ({ target: { files } }) => {
    const { name } = files[0];
    await ffmpeg.load();
    ffmpeg.FS('writeFile', name, await fetchFile(files[0]));
    await ffmpeg.run('-f', 'gif', '-i', name, 'output.mp4');
    const data = ffmpeg.FS('readFile', 'output.mp4');
    const video = document.getElementById('player');
    video.src = URL.createObjectURL(
      new Blob([data.buffer], { type: 'video/mp4' }),
    );
  });
Enter fullscreen mode Exit fullscreen mode

Here is the demo and here is the source

Note

  • There could be additional flags supplied to ffmpeg to limit the frame rate, height and width of the video file...
💖 💪 🙅 🚩
rafi993
Rafi

Posted on November 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Converting GIF to MP4
gif Converting GIF to MP4

November 15, 2020