Reduce video file size in Flutter / Dart

Viewed 6295

I am working on an application where users can upload videos to our server. They can select videos from their gallery, so I would like to reduce them before uploading.

I would like to know if there is any way to reduce the video file size with Flutter/ Dart. Thanks.

4 Answers

Update: since my original answer, there's another package https://pub.dev/packages/flutter_video_compress with friendlier API

https://pub.dartlang.org/packages/flutter_ffmpeg is pretty good, and has well-documented instruction

import 'package:flutter_ffmpeg/flutter_ffmpeg.dart';

 final FlutterFFmpeg _flutterFFmpeg = new FlutterFFmpeg();

 _flutterFFmpeg.execute("-i file1.mp4 -c:v mpeg4 file2.mp4").then((rc) => print("FFmpeg process exited with rc $rc"));

Check the rc code, and if it's successful, open file2.mp4, which is the compressed/processed file.

I am using flutter_ffmpeg plugin detailed:

static Future<String> ReduceSizeAndType(videoPath, outDirPath) async {
    assert(File(videoPath).existsSync());

    final arguments = '-y -i $videoPath ' +
        '-preset ultrafast -g 48 -sc_threshold 0 ' +
        '-c:v libx264 -b:v 720k ' +
        '-c:a copy ' +
        '"$outDirPath/file2.mp4"';

    final int rc = await _encoder.execute(arguments);
    assert(rc == 0);

    return outDirPath;
  }

You can change the quality and size of your video with increasing and decreasing 720k quantity. Returned of "$outDirPath" is your output video path.

Use flutter_video_compress package

Installing:

add flutter_video_compress as a dependency in your pubspec.yaml file.

Usage :

Create an instance

final _flutterVideoCompress = FlutterVideoCompress();

Get thumbnail from video path

final uint8list = await _flutterVideoCompress.getThumbnail(
  file.path,
  quality: 50, // default(100)
  position: -1 // default(-1)
);

Get thumbnail file from video path

final thumbnailFile = await _flutterVideoCompress.getThumbnailWithFile(
  file.path,
  quality: 50, // default(100)
  position: -1 // default(-1)
);

Convert video to a gif

final file = await _flutterVideoCompress.convertVideoToGif(
  videoFile.path,
  startTime: 0, // default(0)
  duration: 5, // default(-1)
  // endTime: -1 // default(-1)
);
print(file.path);

Compression Video

final info = await _flutterVideoCompress.compressVideo(
  file.path,
  quality: VideoQuality.DefaultQuality, // default(VideoQuality.DefaultQuality)
  deleteOrigin: false, // default(false)
);
print(info.toJson().toString());

You can learn more about this package here

Related