How to convert GIF to a mp4 video in Flutter?

Issue

How to convert GIF to a mp4 video in Flutter? With flutter_ffmpeg or any other packages.

Solution

Method 1:

Using flutter_ffmpeg is really easy and you can do a lot of other things with the package.

To set up the package add this in pubspec.yaml

dependencies:
  flutter_ffmpeg: ^0.4.2

add this in your build.gradle located here android/build.gradle

ext {
    flutterFFmpegPackage  = "min"
}

finally in your code

import 'package:flutter_ffmpeg/flutter_ffmpeg.dart';
  ...
  ...
  final FlutterFFmpeg _flutterFFmpeg = FlutterFFmpeg();
  final String inputFile = ".../input.gif"; //path of the gif file.
  final String outputFile = ".../output.mp4"; //path to export the mp4 file.

  await _flutterFFmpeg
        .execute("-f gif -i $inputFile $outputFile")
        .then((rc) => print("FFmpeg process 1 exited with rc $rc"));

Note: If you are exporting anywhere other than your app’s directory, the file would have to be scanned or you wouldn’t be able to use the file.

Method 2:

If all you wanna do is convert a .gif to .mp4 then you can save a lot of space by just renaming .gif to .mp4 and it’ll work. You can also rename the same file from .mp4 to .gif. But, this method wouldn’t work if you wanna convert an original .mp4 file to .gif.

Here’s an example on how to rename a file:

  Directory appDocDir = await getApplicationDocumentsDirectory();
  String appDocPath = appDocDir.path;
  //Let's assume that "$appDocPath/awesome.gif" is the path of the file.
  await File("$appDocPath/awesome.gif").rename("$appDocPath/awesome.mp4");

NOTE : You have to enter the full path of the file in rename().

You can again rename the same file back to .gif, and it would work. But, this method wouldn’t work if you want to convert an .mp4 file that was never converted from a .gif.

Answered By – Shaan Mephobic

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.