DEV Community

Rafi
Rafi

Posted on

10 4

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...

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

Collapse
 
arun4033622 profile image
Arun Kumar

Wow :O

Collapse
 
maxprogramming profile image
Max Programming

It does not seem to work right now. There is some CORS issue

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more