Converting GIF to MP4
Rafi
Posted on November 15, 2020
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' }),
);
});
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...
💖 💪 🙅 🚩
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.