In this blog we will learn that how to Implement light Compressor In Flutter and make video files smaller without losing quality by using the light_compressor package.
You may also check our flutter app development company page.

How it works :-
When a video file from the library is compressed, this checks if the user wants to specify a minimum bitrate to prevent low quality video from being compressed. This is useful if you don’t want the video to be compressed every time it is processed to avoid having very poor quality after several rounds of compression.The minimum bitrate selected is 2mbps.
You can provide one of five video qualities: very_high, high, medium, low, or very_low, and the plugin will handle creating the appropriate bitrate number for the output video.
Implementation:-
First we need to create a new flutter project and add the following dependencies in the pubspec.yaml file.
dependencies: flutter sdk: flutter light_compressor: ^2.0.1
iOS
Add the following to your Info.plist file, located in <project root>/ios/Runner/Info.plist
:
<key>NSPhotoLibraryUsageDescription</key> <string>${PRODUCT_NAME} library Usage</string>
Android
Add the following permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>
Include this in your Project-level build.gradle file:
allprojects { repositories { maven { url 'https://jitpack.io' } } }
Include this in your Module-level build.gradle file:
implementation 'com.github.AbedElazizShe:LightCompressor:1.2.3'
Then just call [VideoCompressor.start()] and pass both source and destination file paths. The method has a callback for 5 functions;
OnSuccess — called when compression completed with no errors/exceptions.
OnFailure — called when an exception occured or video bitrate and size are below the minimum required for compression.
OnCancelled — called when the job is cancelled.
If you want to maintain the original video width and height from being modified during compression, you may pass true or false for keepOriginalResolution, with the default being false.
final dynamic response = await _lightCompressor.compressVideo( path: _filePath!, videoQuality: VideoQuality.medium, isMinBitrateCheckEnabled: false, video: Video(videoName: videoName), android: AndroidConfig(isSharedStorage: true, saveAt: SaveAt.Movies), ios: IOSConfig(saveInGallery: false), );
Get Compressor progress to get the stream when the video is being compressed.
StreamBuilder<double>( stream: _lightCompressor.onProgressUpdated, builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { if (snapshot.data != null && snapshot.data > 0) { // --> use snapshot.data } }, ),
complete code:-
import 'dart:async'; import 'dart:io'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:light_compressor/light_compressor.dart'; void main() { runApp(MyApp()); } /// A widget that uses LightCompressor library to compress videos class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { late String _desFile; String? _displayedFile; late int _duration; String? _failureMessage; String? _filePath; bool _isVideoCompressed = false; final LightCompressor _lightCompressor = LightCompressor(); @override Widget build(BuildContext context) => MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text('Compressor Sample'), ), body: Container( margin: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ if (_filePath != null) Text( 'Original size: ${_getVideoSize(file:File(_filePath.toString()))} MB', style: const TextStyle(fontSize: 16), ), const SizedBox(height: 8), if (_isVideoCompressed) Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Size after compression: ${_getVideoSize(file: File(_desFile))} MB', style: const TextStyle(fontSize: 16), ), const SizedBox(height: 8), Text( 'Duration: $_duration seconds', style: const TextStyle(fontSize: 16, color: Colors.red), ), ], ), const SizedBox(height: 16), Visibility( visible: !_isVideoCompressed, child: StreamBuilder<double>( stream: _lightCompressor.onProgressUpdated, builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { if (snapshot.data != null && snapshot.data > 0) { return Column( children: <Widget>[ LinearProgressIndicator( minHeight: 8, value: snapshot.data / 100, ), const SizedBox(height: 8), Text( '${snapshot.data.toStringAsFixed(0)}%', style: const TextStyle(fontSize: 20), ) ], ); } return const SizedBox.shrink(); }, ), ), const SizedBox(height: 24), Text( _failureMessage ?? '', ) ], ), ), floatingActionButton: FloatingActionButton.extended( onPressed: () => _pickVideo(), label: const Text('Pick Video'), icon: const Icon(Icons.video_library), backgroundColor: const Color(0xFFA52A2A), ), ), ); Future<void> _pickVideo() async { _isVideoCompressed = false; final FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.video, ); final PlatformFile ? file = result?.files.first; if (file == null) { return; } _filePath = file.path; setState(() { _failureMessage = null; }); final String videoName = 'MyVideo-${DateTime.now().millisecondsSinceEpoch}.mp4'; final Stopwatch stopwatch = Stopwatch()..start(); final dynamic response = await _lightCompressor.compressVideo( path: _filePath!, videoQuality: VideoQuality.medium, isMinBitrateCheckEnabled: false, video: Video(videoName: videoName), android: AndroidConfig(isSharedStorage: true, saveAt: SaveAt.Movies), ios: IOSConfig(saveInGallery: false), ); stopwatch.stop(); final Duration duration = Duration(milliseconds: stopwatch.elapsedMilliseconds); _duration = duration.inSeconds; if (response is OnSuccess) { setState(() { _desFile = response.destinationPath; _displayedFile = _desFile; _isVideoCompressed = true; }); } else if (response is OnFailure) { setState(() { _failureMessage = response.message; }); } else if (response is OnCancelled) { print(response.isCancelled); } } } String _getVideoSize({required File file}) => formatBytes(file.lengthSync(), file.readAsBytesSync().lengthInBytes); formatBytes(int lengthSync, int i) { final kb = lengthSync / 1024; final mb = kb / 1024; return mb.toString(); }
Output:-
Conclusion:-
We have done with the implementation how to Implement light Compressor In Flutter.
Check here for more interesting blogs –https://mobikul.com/blog/.
Hope this blog helped you to better understand the Implement light Compressor In Flutter.
Thanks for reading this blog.
References:-
https://pub.dev/packages/light_compressor
Be the first to comment.