flutter_video_compress 0.3.7+8

flutter_video_compress #

Generate a new path by compressed video, Choose to keep the source video or delete it by a parameter. Get video thumbnail from a video path and provide video information. Easy to deal with compressed video. Considering reduce application size is not using FFmpeg in IOS.

pub version license android min Sdk Version ios min target

flutter compress video

languages #

English 简体中文 日本語

Usage #

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

dependencies:
  flutter_video_compress: ^0.3.x

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)
);
debugPrint(file.path);

Get media information

only support video now.

final info = await _flutterVideoCompress.getMediaInfo(file.path);
debugPrint(info.toJson().toString());

Compression Video

Compatible with IOS, Android and Web after compression.

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

Check Compressing state

_flutterVideoCompress.isCompressing

Stop compression

Will print InterruptedException in android, but not affect to use.

await _flutterVideoCompress.cancelCompression()

delete all cache files

Delete all files generated by this will delete all files located at 'flutter_video_compress', you shoule ought to know what are you doing.

await _flutterVideoCompress.deleteAllCache()

Subscribe the compression progress steam

class ... extends State<MyApp> {
  Subscription _subscription;

  @override
  void initState() {
    super.initState();
    _subscription =
        _flutterVideoCompress.compressProgress$.subscribe((progress) {
      debugPrint('progress: $progress');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _subscription.unsubscribe();
  }
}

Methods #

FunctionsParametersDescriptionReturns
getThumbnailString path[video path], int quality(1-100)[thumbnail quality], int position[Get a thumbnail from video position]get thumbnail from video pathFuture<Uint8List>
getThumbnailWithFileString path[video path], int quality(1-100)[thumbnail quality], int position[Get a thumbnail from video position]get thumbnail file from video pathFuture<File>
convertVideoToGifString path[video path], int startTime(from 0 start)[convert video to gif start time], int endTime[convert video to gif end time], int duration[convert video to gif duration from start time]convert video to gif from video pathFuture<File>
getMediaInfoString path[video path]get media information from video pathFuture<MediaInfo>
compressVideoString path[video path], VideoQuality quality[compressed video quality], bool deleteOrigin[delete the origin video], int startTime[compression video start time], int duration[compression video duration from start time], bool includeAudio[is include audio in compressed video], int frameRate[compressed video frame rate]compression video at origin video pathFuture<MediaInfo>
cancelCompressionnonecancel compressingFuture<void>
deleteAllCachenoneDelete all files generated by 'flutter_video_compress' will delete all files located at 'flutter_video_compress'Future<bool>

Subscriptions #

SubscriptionsDescriptionStream
compressProgress$Subscribe the compression progress steamdouble progress

Notice #

If your application is significantly larger after using the plugin, you can reduce the application size in the following way:

  • exclude x86 related files (./assets)

  • This library not use ffprobe, only used ffmpeg, but the application still has ffprobe, so you will need to exclude (asssets/arm or assets/x86)

add this config in build.gradle:

  • Don't use ignoreAssetsPattern "!x86" in debug mode, will crash on the simulator
android {
  ...
  // Reduce your application size with this configuration
  aaptOptions {
      ignoreAssetsPattern "!x86:!*ffprobe"
  }
  
  buildTypes {
  ...
}

look detail

If your application is not enabled AndroidX, you will need to add the following code to the last line of the android/build.gradle file.

rootProject.allprojects {
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'androidx.core' && !details.requested.name.contains('androidx')) {
                    details.useVersion "1.0.1"
                }
            }
        }
    }
}

If your application not support swift, you need to add the following code in ios/Podfile.

target 'Runner' do
  use_frameworks! # <--- add this
  ...
end

look detail

If your application never used a swift plugin before, maybe you would meet the error, you need to add the following code in ios/Podfile.

The 'Pods-Runner' target has transitive dependencies that include static binaries

pre_install do |installer|
  # workaround for https://github.com/CocoaPods/CocoaPods/issues/3289
  Pod::Installer::Xcode::TargetValidator.send(:define_method, :verify_no_static_framework_transitive_dependencies) {}
end

look detail

if show error of Regift

pre_install do |installer|
  installer.analysis_result.specifications.each do |s|
      if s.name == 'Regift'
        s.swift_version = '4.0'
    # elsif s.name == 'other-Plugin'
    #   s.swift_version = '5.0'
    # else
    #   s.swift_version = '4.0'
      end
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

TODO #

  • [ ] Refactoring ios code to objective-c

Contribute #

Contributions are always welcome!

0.3.7+8 #

  • docs change pubspec.yaml description

0.3.7+7 #

  • docs Better English documentation

0.3.7+6 #

  • docs better example

0.3.7+5 #

  • docs better example

0.3.7+4 #

  • docs better example

0.3.7+3 #

  • docs deleteAllCache api return whether the boolean value is deleted

0.3.7+2 #

  • fix ios path problem
  • fix ios deleteAllCache functional repair
  • docs document deleteAllCache api description
  • fix android ffmpeg keep metadata orientation by -noautorotate command

0.3.7+1 #

  • feat both add api deleteAllCache to delete cache, please do not put other things in the folder of this plugin, it will be cleared

0.3.7 #

  • Breaking change both rename startCompress to compressVideo, stopCompress to cancelCompression
  • feat both compressVideo api add params { int startTime, int duration, bool includeAudio, int frameRate }
  • feat both getMediaInfo returns add orientation
  • fix android getMediaInfo returns height and width flipped
  • fix android different quality compression size
  • style example fixed some problems with example

0.3.6 #

  • docs document ios swift version documents of how to fix Regift
  • refactor android reduce compressing time
  • refactor android remove updateProgress redundant code to improve performance
  • refactor dart change all print to debugPrint to improve release performance

0.3.5+4 #

  • Support latest dependencies

0.3.5+3 #

  • update documents

0.3.5+2 #

  • increased swift version to 5.0

0.3.5+1 #

  • reduced frame rate to 15 on android, use milliseconds for duration

0.3.5 #

  • Breaking change fix The old version does not scale the Android compressed video, That is, the startCompress quality properties has no effect.
  • fix IOS pod dependency Regift
  • feat enum VideoQuality add DefaultQuality, startCompress quality Use the default properties of the old version
  • fix IOS convertVideoToGif file Suffix
  • docs update example

0.3.4+1 #

  • fix example lost the IOS pod dependency Regift

0.3.4 #

  • docs update convertVideoToGif associated document
  • feat Created API for conversion of video files to gif with start time and duration parameters. For Android ffmpeg is used for conversion and for iOS Regift library is used. Also, added an example on how to use the API within example project.

0.3.3+3 #

  • docs update README.md

0.3.3+2 #

  • docs update README.md

0.3.3+1 #

  • docs docs folder to doc

0.3.3 #

  • docs international documentation increased

0.3.2 #

  • fix unsubscribe excess stream error

0.3.1 #

  • fix compressed video is null
  • fix Bad state: Stream has already been listened to
  • fix Video same address cannot be compressed for the second time

0.3.0 #

  • Breaking change refactor ios anderoid lib code
  • feat add getThumbnailWithFile and getMediaInfo api
  • fix android private folder permissions cause possible problems
  • change startCompress api return type

0.2.0+9 #

  • doc update document

0.2.0+8 #

  • doc update document

0.2.0+7 #

  • fix ios getThumbnail path error
  • Better tips of Compressing error
  • Breaking change start Compress api add whether to cancel the parameter

0.2.0+6 #

  • chore update swift 5

0.2.0+5 #

  • fix: fix the wrong Usage

0.2.0+4 #

  • fix: add some suggestions for reduce apk size
  • Breaking change compressVideo api renamed startCompress
  • feat: add stopCompress api
  • update README.md

0.2.0+3 #

no change

0.2.0+2 #

  • fix: IOS fix import AVFoundation

0.2.0+1 #

  • fix: Android video type changed h264

0.2.0 #

  • Breaking change Migrated dependent sdk, Upgraded kotlin and gradle versions
  • fix: solved Android transcoding video error code 8
  • update example/README.md

0.1.7 #

  • docs: Better Readme

0.1.6 #

  • docs: Better documentation

0.1.5 #

  • CHANGELOG.md
  • fix: supported x86 arm64-v8a armeabi armeabi-v7a

0.1.4 #

  • fix:gradle config 'compile' replaced with 'implementation'

0.1.3 #

  • fix: fix ios 4.2 version bugs

0.1.2 #

  • fix: fix ios build swift_version

0.1.1 #

  • chore: update AndroidX

0.1.0 #

  • feature: get vedio thumbnail
  • feature: compress vedio

example/README.md

flutter_video_compress_example #

import 'dart:io';
import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_video_compress/flutter_video_compress.dart';
import 'package:image_picker/image_picker.dart' show ImagePicker, ImageSource;

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _flutterVideoCompress = FlutterVideoCompress();
  Uint8List _image;
  File _imageFile;
  Subscription _subscription;

  @override
  void initState() {
    super.initState();
    _subscription =
        _flutterVideoCompress.compressProgress$.subscribe((progress) {
      debugPrint('progress: $progress');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _subscription.unsubscribe();
  }

  Future<void> _videoPicker() async {
    if (mounted) {
      final file = await ImagePicker.pickVideo(source: ImageSource.camera);
      if (file?.path != null) {
        final thumbnail = await _flutterVideoCompress.getThumbnail(
          file.path,
          quality: 50,
          position: -1,
        );

        setState(() {
          _image = thumbnail;
        });

        final resultFile = await _flutterVideoCompress.getThumbnailWithFile(
          file.path,
          quality: 50,
          position: -1,
        );
        debugPrint(resultFile.path);

        assert(resultFile.existsSync());

        debugPrint('file Exists: ${resultFile.existsSync()}');

        final MediaInfo info = await _flutterVideoCompress.compressVideo(
          file.path,
          deleteOrigin: true,
          quality: VideoQuality.LowQuality,
        );
        debugPrint(info.toJson().toString());
      }
    }
  }

  Future<void> _cancelCompression() async {
    await _flutterVideoCompress.cancelCompression();
  }

  Future<void> _getMediaInfo() async {
    if (mounted) {
      final file = await ImagePicker.pickVideo(source: ImageSource.gallery);
      if (file?.path != null) {
        final info = await _flutterVideoCompress.getMediaInfo(file.path);
        debugPrint(info.toJson().toString());
      }
    }
  }

  Future<void> _convertVideoToGif() async {
    if (mounted) {
      final file = await ImagePicker.pickVideo(source: ImageSource.gallery);
      if (file?.path != null) {
        final info = await _flutterVideoCompress.convertVideoToGif(
          file.path,
          startTime: 0,
          duration: 5,
        );

        debugPrint(info.path);
        setState(() {
          _imageFile = info;
        });
      }
    }
  }

  List<Widget> _builColumnChildren() {
    // dart 2.3 before
    final _list = <Widget>[
      FlatButton(child: Text('take video'), onPressed: _videoPicker),
      FlatButton(child: Text('stop compress'), onPressed: _cancelCompression),
      FlatButton(child: Text('get media info'), onPressed: _getMediaInfo),
      FlatButton(
        child: Text('convert video to gif'),
        onPressed: _convertVideoToGif,
      ),
    ];
    if (_imageFile != null) {
      _list.add(Flexible(child: Image.file(_imageFile)));
    } else if (_image != null) {
      _list.add(Flexible(child: Image.memory(_image)));
    }
    return _list;

    // dart 2.3
    // final _list = [
    //   FlatButton(child: Text('take video'), onPressed: _videoPicker),
    //   FlatButton(child: Text('stop compress'), onPressed: _cancelCompression),
    //   FlatButton(child: Text('get media info'), onPressed: _getMediaInfo),
    //   FlatButton(
    //     child: Text('convert video to gif'),
    //     onPressed: _convertVideoToGif,
    //   ),
    //   if (_imageFile != null)
    //     Flexible(child: Image.file(_imageFile))
    //   else
    //     if (_image != null) Flexible(child: Image.memory(_image))
    // ];
    // return _list;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Plugin example app')),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: _builColumnChildren(),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_video_compress: ^0.3.7+8

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_video_compress/flutter_video_compress.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
89
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
95
Learn more about scoring.

We analyzed this package on Sep 20, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.0
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.2

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
image_picker ^0.6.0+10
video_player ^0.10.1+3