Coder Social home page Coder Social logo

fluttercandies / flutter_image_compress Goto Github PK

View Code? Open in Web Editor NEW
614.0 11.0 211.0 11.23 MB

flutter image compress

License: MIT License

Kotlin 10.68% Ruby 1.91% Dart 74.06% Java 1.94% Go 3.29% Shell 0.90% HTML 0.84% Swift 4.90% TypeScript 0.79% Batchfile 0.68%
flutter compress

flutter_image_compress's Introduction

flutter_image_compress

ImageCompress pub package GitHub license GitHub stars Awesome Flutter FlutterCandies

Compresses image as native plugin (Obj-C/Kotlin). This library works on Android, iOS, macOS, Web, OpenHarmony.

Why don't you use dart to do it

Q:Dart already has image compression libraries. Why use native?

A:For unknown reasons, image compression in Dart language is not efficient, even in release version. Using isolate does not solve the problem.

Platform Features

Feature Android iOS Web macOS OpenHarmony
method: compressWithList
method: compressAssetImage
method: compressWithFile
method: compressAndGetFile
format: jpeg
format: png
format: webp 🌐
format: heic
param: quality 🌐
param: rotate
param: keepExif

Usage

See the pub version.

dependencies:
  flutter_image_compress: <latest_version>

or run this command:

flutter pub add flutter_image_compress

import the package in your code:

import 'package:flutter_image_compress/flutter_image_compress.dart';

Use as:

See full example

There are several ways to use the library api.

  // 1. compress file and get Uint8List
  Future<Uint8List> testCompressFile(File file) async {
    var result = await FlutterImageCompress.compressWithFile(
      file.absolute.path,
      minWidth: 2300,
      minHeight: 1500,
      quality: 94,
      rotate: 90,
    );
    print(file.lengthSync());
    print(result.length);
    return result;
  }

  // 2. compress file and get file.
  Future<File> testCompressAndGetFile(File file, String targetPath) async {
    var result = await FlutterImageCompress.compressAndGetFile(
        file.absolute.path, targetPath,
        quality: 88,
        rotate: 180,
      );

    print(file.lengthSync());
    print(result.lengthSync());

    return result;
  }

  // 3. compress asset and get Uint8List.
  Future<Uint8List> testCompressAsset(String assetName) async {
    var list = await FlutterImageCompress.compressAssetImage(
      assetName,
      minHeight: 1920,
      minWidth: 1080,
      quality: 96,
      rotate: 180,
    );

    return list;
  }

  // 4. compress Uint8List and get another Uint8List.
  Future<Uint8List> testComporessList(Uint8List list) async {
    var result = await FlutterImageCompress.compressWithList(
      list,
      minHeight: 1920,
      minWidth: 1080,
      quality: 96,
      rotate: 135,
    );
    print(list.length);
    print(result.length);
    return result;
  }

About common params

minWidth and minHeight

minWidth and minHeight are constraints on image scaling.

For example, a 4000*2000 image, minWidth set to 1920, minHeight set to 1080, the calculation is as follows:

// Using dart as an example, the actual implementation is Kotlin or OC.
import 'dart:math' as math;

void main() {
  var scale = calcScale(
    srcWidth: 4000,
    srcHeight: 2000,
    minWidth: 1920,
    minHeight: 1080,
  );

  print("scale = $scale"); // scale = 1.8518518518518519
  print("target width = ${4000 / scale}, height = ${2000 / scale}"); // target width = 2160.0, height = 1080.0
}

double calcScale({
  double srcWidth,
  double srcHeight,
  double minWidth,
  double minHeight,
}) {
  var scaleW = srcWidth / minWidth;
  var scaleH = srcHeight / minHeight;
  var scale = math.max(1.0, math.min(scaleW, scaleH));
  return scale;
}

If your image width is smaller than minWidth or height smaller than minHeight, scale will be 1, that is, the size will not change.

rotate

If you need to rotate the picture, use this parameter.

autoCorrectionAngle

This property only exists in the version after 0.5.0.

And for historical reasons, there may be conflicts with rotate attributes, which need to be self-corrected.

Modify rotate to 0 or autoCorrectionAngle to false.

quality

Quality of target image.

If format is png, the param will be ignored in iOS.

format

Supports jpeg or png, default is jpeg.

The format class sign enum CompressFormat.

Heif and webp Partially supported.

Webp

Support android by the system api (speed very nice). The library also supports iOS. However, we're using third-party libraries, it is not recommended due to encoding speed. In the future, libwebp by google (C/C++) may be used to do coding work, bypassing other three-party libraries, but there are no plan for that currently.

HEIF(Heic)

Heif for iOS

Only support iOS 11+.

Heif for Android

Use HeifWriter for the implementation.

Only support API 28+.

And may require hardware encoder support, does not guarantee that all devices above API 28 are available.

inSampleSize

The param is only support android.

For a description of this parameter, see the Android official website.

keepExif

If this parameter is true, EXIF information is saved in the compressed result.

Attention should be paid to the following points:

  1. Default value is false.
  2. Even if set to true, the direction attribute is not included.
  3. Only support jpg format, PNG format does not support.

Result

The result of returning a List collection will not have null, but will always be an empty array.

The returned file may be null. In addition, please decide for yourself whether the file exists.

About List<int> and Uint8List

You may need to convert List<int> to Uint8List to display images.

To use Uint8List, you need import package to your code like this:

img

final image = Uint8List.fromList(imageList);
ImageProvider provider = MemoryImage(Uint8List.fromList(imageList));

Usage in Image Widget:

Future<Widget> _compressImage() async {
  List<int> image = await testCompressFile(file);
  ImageProvider provider = MemoryImage(Uint8List.fromList(image));
  imageWidget = Image(
    image: provider ?? AssetImage('img/img.jpg'),
  );
}

Write to file usage:

Future<void> writeToFile(List<int> image, String filePath) {
  return File(filePath).writeAsBytes(image, flush: true);
}

Runtime Error

Because of some support issues, all APIs will be compatible with format and system compatibility, and an exception (UnsupportedError) may be thrown, so if you insist on using webp and heic formats, please catch the exception yourself and use it on unsupported devices jpeg compression.

Example:

Future<Uint8List> compressAndTryCatch(String path) async {
  Uint8List result;
  try {
    result = await FlutterImageCompress.compressWithFile(
      path,
      format: CompressFormat.heic,
    );
  } on UnsupportedError catch (e) {
    print(e);
    result = await FlutterImageCompress.compressWithFile(
      path,
      format: CompressFormat.jpeg,
    );
  }
  return result;
}

Android

You may need to update Kotlin to version 1.5.21 or higher.

Troubleshooting

Compressing returns null

Sometimes, compressing will return null. You should check if you can read/write the file, and the parent folder of the target file must exist.

For example, use the path_provider plugin to access some application folders, and use a permission plugin to request permission to access SD cards on Android/iOS.

About EXIF information

Using this library, EXIF information will be removed by default.

EXIF information can be retained by setting keepExif to true, but not direction information.

  • PNG/JPEG encoder: System API.
  • WebP encoder:
  • HEIF encoder: System API.

Web

The web implementation is not required for many people,

This plugin uses pica to implement compression.

Currently, debug mode does not allow you to use the dynamic script loading scheme. And when you actually deploy, you may choose server deployment or cdn deployment, so here we suggest you add script node to head or body by yourself in your <flutte_project>/web/index.html.

Add for <flutte_project>/web/index.html:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/pica.min.js" ></script>

<!-- or -->

<script src="https://unpkg.com/pica/dist/pica.min.js" ></script>

About web compatibility: two methods with file will throw an exception when used on the web.

About macOS

You need change the minimum deployment target to 10.15.

Open xcode project, select Runner target, and change the value of macOS Deployment Target to 10.15.

And, change the Podfile: Change platform to platform :osx, '10.15'.

OpenHarmony

The currently supported image formats for parsing include JPEG, PNG, GIF, RAW, WebP, BMP, and SVG. However, the encoding output image formats are currently limited to JPEG, PNG, and WebP only.

当前支持的解析图片格式包括 JPEG、PNG、GIF、RAW、WebP、BMP、SVG . 编码输出图片格式当前仅支持 JPEG、PNG 和 WebP.

flutter_image_compress's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flutter_image_compress's Issues

Compile Error: No named parameter with the name 'onError'.

For some reasons, I can only use the flutter channel beta. (i.e. flutter version >= 1.6.3)

flutter_image_compress version tried: (1) 0.5.2, (2) ref: 5a54.... (3) ref: c3c89.....

And thanks in advance.

pubspec:

  flutter_image_compress:
      git:
        url: https://github.com/OpenFlutter/flutter_image_compress.git
#        ref: 5a545f7e5409d091cd18f5891a8b07426f390729
        ref: c3c891d0be54f0892bcb4e9c4608d7ad1498e73c

Compile Error:

Compiler message:
file:///C:/Users/Administrator/AppData/Roaming/Pub/Cache/git/flutter_image_compress-c3c891d0be54f0892bcb4e9c4608d7ad1498e73c/lib/flutter_image_compress.dart:205:32: Error: No named parameter with the name 'onError'.
  stream.addListener(listener, onError: errorListener);
                               ^^^^^^^
file:///C:/Users/Administrator/AppData/Roaming/Pub/Cache/git/flutter_image_compress-c3c891d0be54f0892bcb4e9c4608d7ad1498e73c/lib/flutter_image_compress.dart:207:27: Error: The argument type 'void Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///C:/Program%20Files/Flutter/SDK/flutter/packages/flutter/lib/src/painting/image_stream.dart').
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///C:/Program%20Files/Flutter/SDK/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
    stream.removeListener(listener);

Flutter Doctor:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel beta, v1.6.3, on Microsoft Windows [Version 10.0.17134.472], locale zh-CN)

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.4)
[!] VS Code, 64-bit edition (version 1.34.0)
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[√] Connected device (1 available)

! Doctor found issues in 1 category.

Exception thrown

When I try to compress, the following error occurs:

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Exception: error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
#0      Window.sendPlatformMessage  (dart:ui/window.dart:868:9)
#1      BinaryMessages._sendPlatformMessage 
package:flutter/…/services/platform_messages.dart:46
#2      BinaryMessages.send 
package:flutter/…/services/platform_messages.dart:97
#3      MethodChannel.invokeMethod 
package:flutter/…/services/platform_channel.dart:295

App force closes

Hi, I tried including flutter_image_compress: ^0.3.1 to my pubspec.yaml without writing any code,
then flutter run, the app successfully builds but force closes on launch when running on real android devices.

I tried adding ext.kotlin_version = '1.3.21' to build.gradle like this:

buildscript {
    ext.kotlin_version = '1.3.21'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.2.0'  // Google Services plugin
    }
}

But same result.
I'm new to flutter and app development, did i missed something?

Out of Memory Error on Android 6.0

We are seeing the following error for our users on Android 6 with Samsung devices. Running version 0.6.2.

Fatal Exception: java.lang.OutOfMemoryError: Failed to allocate a 26211852 byte allocation with 16777216 free bytes and 21MB until OOM
       at dalvik.system.VMRuntime.newNonMovableArray(VMRuntime.java)
       at android.graphics.Bitmap.nativeCreate(Bitmap.java)
       at android.graphics.Bitmap.createBitmap + 975(Bitmap.java:975)
       at android.graphics.Bitmap.createBitmap + 946(Bitmap.java:946)
       at android.graphics.Bitmap.createBitmap + 877(Bitmap.java:877)
       at com.example.flutterimagecompress.ext.BitmapCompressExtKt.compress(BitmapCompressExtKt.java)
       at com.example.flutterimagecompress.ext.BitmapCompressExtKt.compress(BitmapCompressExtKt.java)
       at com.example.flutterimagecompress.ext.BitmapCompressExtKt.compress(BitmapCompressExtKt.java)
       at com.example.flutterimagecompress.core.CompressFileHandler$handle$1.run(CompressFileHandler.java)
       at java.util.concurrent.ThreadPoolExecutor.runWorker + 1113(ThreadPoolExecutor.java:1113)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run + 588(ThreadPoolExecutor.java:588)
       at java.lang.Thread.run + 818(Thread.java:818)

Our only call to the library is this :

    var result = await FlutterImageCompress.compressWithFile(file.absolute.path,
        rotate: rotationCorrection);

getImageProperties should include image rotation

My use case is to store an image in portrait mode with a certain aspect ratio and size. I noticed that on Android, the getImageProperties does not work as expected for pictures taken in portrait mode. If the image is in portrait mode, I need to crop it in order to get the desired aspect ratio. However, for images taken with the built-in camera in Portrait mode, getImageProperties returns the size as if the image was in landscape mode. In order to process this case correctly, I need to know the rotation of the image. ImageProperties would be the appropriate place to add the rotation attribute.

Android build error

Flutter v 1.8.1
Kotlin v 1.3.41
Android Studio v 3.4.2
Mac OS 10.14.5

What other info should I provide to help determine what's causing the following error...? Thanks

Running flutter build apk --release emits the following information:

admins-MBP:diary_app_flutter chris$ flutter build apk --release
You are building a fat APK that includes binaries for android-arm, android-arm64.
If you are deploying the app to the Play Store, it's recommended to use app bundles or split the APK to reduce the APK size.
To generate an app bundle, run:
flutter build appbundle --target-platform android-arm,android-arm64
Learn more on: https://developer.android.com/guide/app-bundle
To split the APKs per ABI, run:
flutter build apk --target-platform android-arm,android-arm64 --split-per-abi
Learn more on: https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split
Initializing gradle... 0.9s
Resolving dependencies... 9.5s
Note: /Users/chris/development/flutter/.pub-cache/hosted/pub.dartlang.org/connectivity-0.4.3+1/android/src/main/java/io/flutter/plugins/connectivity/ConnectivityPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
e: /Users/chris/development/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.6.2/android/src/main/kotlin/com/example/flutterimagecompress/FlutterImageCompressPlugin.kt: (25, 76): Type mismatch: inferred type is Activity! but AppCompatActivity was expected
e: /Users/chris/development/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.6.2/android/src/main/kotlin/com/example/flutterimagecompress/FlutterImageCompressPlugin.kt: (26, 76): Type mismatch: inferred type is Activity! but AppCompatActivity was expected
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done 82.4s
Gradle task assembleRelease failed with exit code 1

Here's the dependency list from my flutter project yaml file:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0+2
  cupertino_icons: ^0.1.2
  shared_preferences: 0.5.2+1
  connectivity: 0.4.3+1
  flutter_launcher_icons: "^0.7.0"
  package_info: ^0.4.0+3
  intl: ^0.15.8
  palette_generator: ^0.1.1
  uuid: ^2.0.1
  image_picker: ^0.4.10
  camera: ^0.4.2
  flutter_image_compress: ^0.6.2
  # image_gallery_saver: ^1.1.0

Build failed with exception

Hi,
I just upgraded to latest flutter stable 1.7.8hotfix3 and also to flutter_image_compress 0.6.3, now I get this when trying to build:


Initializing gradle... 1,0s
Resolving dependencies... 4,6s
Launching lib/main.dart on ANE LX1 in release mode...
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
e: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_image_compress-0.6.2\android\src\main\kotlin\com\example\flutterimagecompress\FlutterImageCompressPlugin.kt: (11, 7): Redeclaration: FlutterImageCompressPlugin
e: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_image_compress-0.6.2\android\src\main\kotlin\com\example\flutterimagecompress\core\CompressFileHandler.kt: (15, 7): Redeclaration: CompressFileHandler
e: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_image_compress-0.6.2\android\src\main\kotlin\com\example\flutterimagecompress\core\CompressListHandler.kt: (17, 7): Redeclaration: CompressListHandler
e: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_image_compress-0.6.3\android\src\main\kotlin\com\example\flutterimagecompress\FlutterImageCompressPlugin.kt: (11, 7): Redeclaration: FlutterImageCompressPlugin
e: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_image_compress-0.6.3\android\src\main\kotlin\com\example\flutterimagecompress\FlutterImageCompressPlugin.kt: (25, 76): Type mismatch: inferred type is PluginRegistry.Registrar but Activity was expected
e: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_image_compress-0.6.3\android\src\main\kotlin\com\example\flutterimagecompress\FlutterImageCompressPlugin.kt: (26, 76): Type mismatch: inferred type is PluginRegistry.Registrar but Activity was expected
e: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_image_compress-0.6.3\android\src\main\kotlin\com\example\flutterimagecompress\core\CompressFileHandler.kt: (15, 7): Redeclaration: CompressFileHandler
e: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_image_compress-0.6.3\android\src\main\kotlin\com\example\flutterimagecompress\core\CompressListHandler.kt: (17, 7): Redeclaration: CompressListHandler

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':flutter_image_compress:compileReleaseKotlin'.

Compilation error. See log for more details

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 15s


Kotlin: 1.3.41

Any idea? :)

Crash in flutter v1.5.9

file:///Users/dingzuhua/.pub-cache/hosted/pub.flutter-io.cn/flutter_image_compress-0.4.0/lib/flutter_image_compress.dart:188:16: Error: The argument type 'String' can't be assigned to the parameter type 'DiagnosticsNode'.
- 'DiagnosticsNode' is from 'package:flutter/src/foundation/diagnostics.dart' ('file:///Users/dingzuhua/flutter/packages/flutter/lib/src/foundation/diagnostics.dart').
Try changing the type of the parameter, or casting the argument to 'DiagnosticsNode'.
context: 'image load failed ',

Running flutter doctor...
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel master, v1.5.9-pre.196, on Mac OS X 10.14.4 18E226, locale
zh-Hans-CN)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.2.1)
[✓] Android Studio (version 3.2)
[✓] IntelliJ IDEA Ultimate Edition (version 2018.1)
[✓] Connected device (1 available)

• No issues found!

Images Compression crashes Android

With the latest version 0.5.1 I get sometimes a crash when compressing a JPEG image on Android. Didn't test if it works with a version before that. The code is here:

Future<File> _compressImage(File image) async {
    final tempDir = await getTemporaryDirectory();
    final compressedFile = await FlutterImageCompress.compressAndGetFile(
      image.absolute.path,
      '${tempDir.path}/${basename(image.path)}',
      quality: 90,
    );
    return compressedFile.lengthSync() < image.lengthSync() ? compressedFile : image;
  }

And the exception is here:

E/AndroidRuntime(21107): FATAL EXCEPTION: pool-4-thread-2
E/AndroidRuntime(21107): Process: com.example.example, PID: 21107
E/AndroidRuntime(21107): java.lang.IndexOutOfBoundsException: Invalid index 65542, size is 65536
E/AndroidRuntime(21107): 	at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
E/AndroidRuntime(21107): 	at java.util.ArrayList.get(ArrayList.java:308)
E/AndroidRuntime(21107): 	at com.example.flutterimagecompress.ExifKt.getUint16(Exif.kt:4)
E/AndroidRuntime(21107): 	at com.example.flutterimagecompress.ExifKt.access$getUint16(Exif.kt:1)
E/AndroidRuntime(21107): 	at com.example.flutterimagecompress.Exif.getRotationDegrees(Exif.kt:51)
E/AndroidRuntime(21107): 	at com.example.flutterimagecompress.CompressFileHandler$handleGetFile$1.run(CompressFileHandler.kt:58)
E/AndroidRuntime(21107): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
E/AndroidRuntime(21107): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
E/AndroidRuntime(21107): 	at java.lang.Thread.run(Thread.java:818)

android Picture path "/storage/emulated/0/Pictures/Screenshots/xxx..jpg" errors

I/CrashReport(31090): Set native info: isAppForeground(true)
W/ServiceManagement(31090): getService: unable to call into hwbinder service for vendor.huawei.hardware.jpegdec@1.0::IJpegDecode/default.
D/mali_winsys(31090): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
D/mali_winsys(31090): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
E/flutter (31090): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The getter 'path' was called on null.
E/flutter (31090): Receiver: null
E/flutter (31090): Tried calling: path
E/flutter (31090): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)

but I changed to another android devices. the picture path , it works well.

"/storage/emulated/0/DCIM/Camera/IMG_xxx.jpg"

my AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Missing function "getImageProperties"

In my app I want to scale all large images to some smaller size e.g. 1920x1024. But I don't want to touch images which are already of that size or smaller. This plugin allows specifying only minimum size so it will also stretch small images to larger size which I don't want to happen.

So what I am missing is a lightweight method for getting the current image size. Wouldn't this kind of function be logical part of this plugin? Here is one sample how to get image dimensions in Android: https://stackoverflow.com/questions/11128481/android-get-image-dimensions-without-opening-it

There are some other plugins to get image properties, but none of them what I have found do it "correctly" (they read the whole image in memory which is no-go for my app).

Same image quality for iOS and Android

When passing the quality parameter to a compression function of flutter_image_compress, the compression seems to be different on iOS than on Android.

Is there a way to achieve the same quality on both platforms?

I took a picture on iOS and on Android, here are the compression results:
iOS
1690.8486328125kb => 239.123046875kb

Android:
967.0029296875kb => 573.7646484375kb

So there is more compression on iOS than on Android.

Do I need to maintain different quality values depending on iOS or Android?
Or is it a feature going into this library?

非常抱歉,提了个无关该项目的issues

你好,首先非常抱歉在该项目下提一个无关的issues。

我在发布flutter插件的时候遇到了一些问题,然后参照了你的这篇文章
"https://blog.csdn.net/qq_28478281/article/details/87283345。"
确保的curl google.com返回信息,使用flutter packages pub publish --dry-run 返回的第一行提示为"Publishing flutter_encrypt_lib 1.0.0 to https://pub.dartlang.org:"。

然后使用"flutter packages pub publish --server=https://pub.dartlang.org",输入"y",返回了一个url认证,点击链接后,控制台一直显示
"
Waiting for your authorization...
Authorization received, processing...
It looks like accounts.google.com is having some trouble.
Pub will wait for a while before trying to connect again.
OS Error: Operation timed out, errno = 60, address = accounts.google.com, port = 55083
pub finished with exit code 69
"
能获取一下你的帮助嘛?多谢了。
以下是"flutter doctor"
[✓] Flutter (Channel stable, v1.5.4-hotfix.2, on Mac OS X 10.14.4 18E226, locale zh-Hans-CN)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.2.1)
[✓] Android Studio (version 3.4)
[!] Proxy Configuration
! NO_PROXY is not set
[✓] Connected device (1 available)
再次感谢你查看我的issues

The argument type 'String' can't be assigned to the parameter type 'DiagnosticsNode'

Hi, I cannot build my flutter app with 'flutter_image_compress 0.4.0'.

The error message is

file:///Users/dokinkon/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.4.0/lib/flutter_image_compress.dart:188:16: Error: The argument type 'String' can't be assigned to the parameter type 'DiagnosticsNode'.

  • 'DiagnosticsNode' is from 'package:flutter/src/foundation/diagnostics.dart' ('file:///Users/dokinkon/Case/flutter/packages/flutter/lib/src/foundation/diagnostics.dart').
    Try changing the type of the parameter, or casting the argument to 'DiagnosticsNode'.
    context: 'image load failed ',

I guess this issue maybe caused by the change of flutter SDK? Thanks.

Below is my flutter doctor:
Running flutter doctor...
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel master, v1.5.9-pre.124, on Mac OS X 10.14.4 18E226, locale zh-Hant-TW)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[!] iOS toolchain - develop for iOS devices (Xcode 10.2.1)
✗ Verify that all connected devices have been paired with this computer in Xcode.
If all devices have been paired, libimobiledevice and ideviceinstaller may require updating.
To update with Brew, run:
brew update
brew uninstall --ignore-dependencies libimobiledevice
brew uninstall --ignore-dependencies usbmuxd
brew install --HEAD usbmuxd
brew unlink usbmuxd
brew link usbmuxd
brew install --HEAD libimobiledevice
brew install ideviceinstaller
[✓] Android Studio (version 3.4)
[✓] VS Code (version 1.33.1)
[✓] Connected device (1 available)

Calling compressWithList returns null

image
i set the ImageByteFormat to ImageByteFormat.rawRgba,Calling compressWithList returns null;
if i set the ImageByteFormat to ImageByteFormat.png,Calling compressWithList returns the correct result

[Android] path Must not be null

Crashes on Android. iOS works fine.
To get the image I use image_picker and pick the image from gallery. If I pick from camera it works fine, so the issue is only when getting the image from gallery.

I/flutter (19871): The following ArgumentError was thrown:
I/flutter (19871): Invalid argument(s) (path): Must not be null
I/flutter (19871): 
I/flutter (19871): When the exception was thrown, this was the stack:
I/flutter (19871): #0      ArgumentError.checkNotNull (dart:core/errors.dart:181:27)
I/flutter (19871): #1      new _File (dart:io/file_impl.dart:210:19)
I/flutter (19871): #2      new File (dart:io/file.dart:255:18)
I/flutter (19871): #3      FlutterImageCompress.compressAndGetFile (package:flutter_image_compress/flutter_image_compress.dart:90:12)
I/flutter (19871): <asynchronous suspension>

flutter doctor -v:

[✓] Flutter (Channel stable, v1.2.1, on Mac OS X 10.14.4 18E226, locale en-GB)
    • Flutter version 1.2.1 at /Users/tudor/dev/flutter
    • Framework revision 8661d8aecd (9 weeks ago), 2019-02-14 19:19:53 -0800
    • Engine revision 3757390fa4
    • Dart version 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/tudor/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • ANDROID_HOME = /Users/tudor/Library/Android/sdk
    • Java binary at: /Users/tudor/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/182.5314842/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.2, Build version 10E125
    • ios-deploy 1.9.4
    • CocoaPods version 1.6.1

[✓] Android Studio (version 3.3)
    • Android Studio at /Users/tudor/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/182.5314842/Android Studio.app/Contents
    • Flutter plugin version 34.0.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] Connected device (1 available)
    • SM G950F • 988a1644544d44384c • android-arm64 • Android 9 (API 28)

• No issues found!

autoCorrectionAngle switches image width and height

I am using this library to compress an in-memory image to a certain width:

final compressedBytes = await FlutterImageCompress.compressWithList(
      bytes,
      minWidth: targetWidth,
      minHeight: 0,
    );

On some Android devices (i.e. Samsung Galaxy S6) I have a problem with resulting image size - height is equal to targetWidth and width is scaled to keep the aspect ratio.

I think that the problem is caused by autoCorrectionAngle - it rotates the image to keep orientation (which is what I want), but it does not adjust width and height values to the rotation.

Would it be possible to change the behaviour of auto correcting orientation to also switch width with height if needed, so that resulting image width is equal to targetWidth I specify? If not - is there a way for me to know which image will be rotated by autoCorrectionAngle = true so that I can specify a targetHeight instead of targetWidth to achieve the same result?

Image take in portrait mode is rotated 90 degrees

Hello,

When I take photo in portrait mode a apply "compressWithFile", I end up with compressed image rotated 90 degrees counterclockwise.

Tested platform: Android

Flutter doctor:
[✓] Flutter (Channel unknown, v0.9.5, on Linux, locale en_US.utf8)
• Flutter version 0.9.5 at /opt/flutter-sdk
• Framework revision 020fd590b0 (3 weeks ago), 2018-09-26 14:28:26 -0700
• Engine revision 38a646e14c
• Dart version 2.1.0-dev.5.0.flutter-4cf2d3990b

[!] Android toolchain - develop for Android devices (Android SDK 28.0.1)
• Android SDK at /opt/android-sdk/
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.1
• ANDROID_HOME = /opt/android-sdk/
• Java binary at: /opt/android-studio/jre/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)
✗ Android license status unknown.

[✓] Android Studio (version 3.1)
• Android Studio at /opt/android-studio
• Flutter plugin version 27.1.1
• Dart plugin version 173.4700
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)

[✓] IntelliJ IDEA Ultimate Edition (version 2018.2)
• IntelliJ at /opt/idea
• Flutter plugin version 29.0.4
• Dart plugin version 182.4505.50

[✓] Connected device (1 available)
• Nokia 6.1 • android-arm64 • Android 8.1.0 (API 27)

Optimize memory usage of compressAndGetFile

The code in BitmapCompressExt.kt always creates the whole bitmap in memory (ByteArrayOutputStream) even if final output is wanted in a file. I think it would be better to pass FileOutputStream directly to Bitmap.compress, something like this:

val fos = FileOutputStream(outputFilePath)
Bitmap.createScaledBitmap(this, destW, destH, true)
        .rotate(rotate)
        .compress(Bitmap.CompressFormat.JPEG, quality, fos)
fos.close()

I believe that would consume much less memory.

Would you consider doing an image resize?

I found this library extremely slow and memory consuming: https://pub.dartlang.org/packages/image

Was wondering if you would consider adding some resize APIs, my use case is uploading pictures to Firebase, and I need to find the smallest file-size possible. Users could select images of anywhere between 100KB to 5MB, so I would like to do a resize to width: 1080 (like what instagram does)

Thank you.

Compiler failed

Compiler message:
file:///Users/rocketmonkey/dev/flutter/.pub-cache/hosted/pub.dartlang.org/cached_network_image-0.4.2/lib/cached_network_image.dart:199:38: Error: The argument type 'void Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/painting/image_stream.dart').
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
      oldImageStream?.removeListener(_handleImageChanged);
                                     ^
file:///Users/rocketmonkey/dev/flutter/.pub-cache/hosted/pub.dartlang.org/cached_network_image-0.4.2/lib/cached_network_image.dart:200:32: Error: The argument type 'void Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/painting/image_stream.dart').
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
      _imageStream.addListener(_handleImageChanged);
                               ^
file:///Users/rocketmonkey/dev/flutter/.pub-cache/hosted/pub.dartlang.org/cached_network_image-0.4.2/lib/cached_network_image.dart:210:34: Error: The argument type 'void Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/painting/image_stream.dart').
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
    _imageStream?.removeListener(_handleImageChanged);
                                 ^
file:///Users/rocketmonkey/dev/flutter/.pub-cache/hosted/pub.dartlang.org/cached_network_image-0.4.2/lib/cached_network_image.dart:464:31: Error: The argument type 'Null Function(StringBuffer)' can't be assigned to the parameter type 'Iterable<DiagnosticsNode> Function()'.
 - 'StringBuffer' is from 'dart:core'.
 - 'Iterable' is from 'dart:core'.
 - 'DiagnosticsNode' is from 'package:flutter/src/foundation/diagnostics.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/foundation/diagnostics.dart').
Try changing the type of the parameter, or casting the argument to 'Iterable<DiagnosticsNode> Function()'.
        informationCollector: (StringBuffer information) {
                              ^
file:///Users/rocketmonkey/dev/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.2.4/lib/flutter_image_compress.dart:166:16: Error: The argument type 'String' can't be assigned to the parameter type 'DiagnosticsNode'.
 - 'DiagnosticsNode' is from 'package:flutter/src/foundation/diagnostics.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/foundation/diagnostics.dart').
Try changing the type of the parameter, or casting the argument to 'DiagnosticsNode'.
      context: 'image load failed ',
               ^
file:///Users/rocketmonkey/dev/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.2.4/lib/flutter_image_compress.dart:174:32: Error: No named parameter with the name 'onError'.
  stream.addListener(listener, onError: errorListener);
                               ^^^^^^^
file:///Users/rocketmonkey/dev/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.2.4/lib/flutter_image_compress.dart:176:27: Error: The argument type 'void Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/painting/image_stream.dart').
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/rocketmonkey/dev/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
    stream.removeListener(listener);

iOS run error

/Users/bingbing/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.1.2/ios/Classes/CompressFileHandler.h:9:27: Expected a type
/Users/bingbing/Documents/project/assistant-app/ios/Runner/GeneratedPluginRegistrant.m:8:9: While building module 'flutter_image_compress' imported from /Users/bingbing/Documents/project/assistant-app/ios/Runner/GeneratedPluginRegistrant.m:8:
/Users/bingbing/Documents/project/assistant-app/ios/:1:9: In file included from :1:
/Users/bingbing/Documents/project/assistant-app/ios/Pods/Target Support Files/flutter_image_compress/flutter_image_compress-umbrella.h:13:9: In file included from /Users/bingbing/Library/Developer/Xcode/DerivedData/Runner-fvjzjegktdfhfmggngiyngnhzjvp/Build/Products/Debug-iphonesimulator/flutter_image_compress/flutter_image_compress.framework/Headers/flutter_image_compress-umbrella.h:13:
/Users/bingbing/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.1.2/ios/Classes/CompressFileHandler.h:11:35: Expected a type
/Users/bingbing/Documents/project/assistant-app/ios/Runner/GeneratedPluginRegistrant.m:8:9: While building module 'flutter_image_compress' imported from /Users/bingbing/Documents/project/assistant-app/ios/Runner/GeneratedPluginRegistrant.m:8:
/Users/bingbing/Documents/project/assistant-app/ios/:1:9: In file included from :1:
/Users/bingbing/Documents/project/assistant-app/ios/Pods/Target Support Files/flutter_image_compress/flutter_image_compress-umbrella.h:13:9: In file included from /Users/bingbing/Library/Developer/Xcode/DerivedData/Runner-fvjzjegktdfhfmggngiyngnhzjvp/Build/Products/Debug-iphonesimulator/flutter_image_compress/flutter_image_compress.framework/Headers/flutter_image_compress-umbrella.h:13:
/Users/bingbing/.pub-cache/hosted/pub.dartlang.org/flutter_image_compress-0.1.2/ios/Classes/CompressListHandler.h:12:27: Expected a type
/Users/bingbing/Documents/project/assistant-app/ios/Runner/GeneratedPluginRegistrant.m:8:9: While building module 'flutter_image_compress' imported from /Users/bingbing/Documents/project/assistant-app/ios/Runner/GeneratedPluginRegistrant.m:8:
/Users/bingbing/Documents/project/assistant-app/ios/:1:9: In file included from :1:
/Users/bingbing/Documents/project/assistant-app/ios/Pods/Target Support Files/flutter_image_compress/flutter_image_compress-umbrella.h:15:9: In file included from /Users/bingbing/Library/Developer/Xcode/DerivedData/Runner-fvjzjegktdfhfmggngiyngnhzjvp/Build/Products/Debug-iphonesimulator/flutter_image_compress/flutter_image_compress.framework/Headers/flutter_image_compress-umbrella.h:15:
/Users/bingbing/Documents/project/assistant-app/ios/Runner/GeneratedPluginRegistrant.m:8:9: Could not build module 'flutter_image_compress'

i get an exception

[ERROR:flutter/lib/ui/painting/codec.cc(91)] InitCodec failed - buffer was empty

Future<List> testCompressFile(File file) async {
var result = await FlutterImageCompress.compressWithFile(file.absolute.path,
minWidth: 700, quality: 80, rotate: 90);
print(file.lengthSync());
print(result.length);
return result;
}

console

I/flutter (26332): 3465236
I/flutter (26332): 0
E/flutter (26332): [ERROR:flutter/lib/ui/painting/codec.cc(91)] InitCodec failed - buffer was empty
I/flutter (26332): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
I/flutter (26332): The following _Exception was thrown resolving an image codec:
I/flutter (26332): Exception: operation failed
I/flutter (26332): ════════════════════════════════════════════════════════════════════════════════════════════════════

Error building App for Android

When running flutter build apk I'm getting this error:

Unable to resolve dependency for ':app@dynamicProfile/compileClasspath': Could not resolve project :flutter_image_compress.
Unable to resolve dependency for ':app@dynamicProfileUnitTest/compileClasspath': Could not resolve project :flutter_image_compress.
Unable to resolve dependency for ':app@profile/compileClasspath': Could not resolve project :flutter_image_compress.

For iOS works just fine, but Android keeps failing.

The only way to make it work is adding this on the file app/build.graddle

lintOptions {
disable 'InvalidPackage'
checkReleaseBuilds false
}

This happens after I updated to the newer version. Any suggestion?

Compression changes orientation

TL;DR
The plugin strips EXIF information when compressing the image (only tested on Android). This changes orientation for my image.
Example project code is here.

I have the following bug on Android:
If I use any compression function of FlutterImageCompress with rotation: 0, the image is rotated after the compression (although it shouldn't be rotated). In the example where is an image taken with a Samsung GT-I9195.

According to the EXIF information the orientation is 6. This means rotated by 90° counterclockwise.

The original image:

identify -verbose assets/passierte_tomaten_samsung.jpg|grep -i orientation
  Orientation: RightTop
    exif:Orientation: 6

original

The compressed image is missing the orientation in the EXIF information (Android)

identify -verbose apps/com.example.flutterimagecompressbug/r/app_flutter/flutter_image_compress.jpg |grep -i orientation
  Orientation: Undefined

after_compression

I did not check yet, if the EXIF information are also stripped on iOS.

iOS error

Hello, I am getting this error when running on iOS:

...flutter/.pub-cache/git/flutter_image_compress-5a545f7e5409d091cd18f5891a8b07426f390729/lib/flutter_image_compress.dart:205:32: Error: No named parameter with the name 'onError'. ...flutter/.pub-cache/git/flutter_image_compress-5a545f7e5409d091cd18f5891a8b07426f390729/lib/flutter_image_compress.dart:207:27: Error: The argument type 'void Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.

My code:

File processImage({File oldImage}) async {
   final Directory tmpDirectory = await Directory.systemTemp.createTemp();
   File myNewFile = await FlutterImageCompress.compressAndGetFile(
        oldImage.path, tmpDirectory.path,
        quality: 66);
   return myNewFile;
}

flutter doctor -v:

[✓] Flutter (Channel dev, v1.6.3, on Mac OS X 10.14.5 18F132, locale en-BR)
    • Flutter version 1.6.3 at /Users/mauro/development/flutter
    • Framework revision bc7bc94083 (2 days ago), 2019-05-23 10:29:07 -0700
    • Engine revision 8dc3a4cde2
    • Dart version 2.3.2 (build 2.3.2-dev.0.0 e3edfd36b2)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/mauro/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • ANDROID_HOME = /Users/mauro/Library/Android/sdk
    • ANDROID_SDK_ROOT = /Users/mauro/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.2.1, Build version 10E1001
    • ios-deploy 1.9.4
    • CocoaPods version 1.7.0

[✓] Android Studio (version 3.4)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 35.3.1
    • Dart plugin version 183.6270
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

[✓] VS Code (version 1.34.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.0.2

[✓] Connected device (1 available)
    • iPhone Mauro • e1216cebac409d83bc8d37bde15f8af53564c933 • ios • iOS 12.3

performance (isolate)

need a synchronous analogue of the function CompressAndGetFile, for works with isolations. What function would return the File not Future

compile error

Error when compiling:

Error: The argument type 'void Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.

  • 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart'
  • 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///opt/flutter/packages/flutter/lib/src/painting/image_stream.dart').
    Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
    stream.addListener(listener);

getting error on packages get

Since I'm using beta flutter build I'm using dependency you provided but is showing an error. Any idea how to fix it?

Git error. Command: git rev-list --max-count=1 173ce7d73835ce35f695ac859bdabf471d1160e6

fatal: bad object 173ce7d73835ce35f695ac859bdabf471d1160e6

flutter_image_compress:
    git:
      url: https://github.com/OpenFlutter/flutter_image_compress.git
      ref: 173ce7d73835ce35f695ac859bdabf471d1160e6

ios exception

when I use the camera function, the app flashes directly and throws the following error:Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.

iOS crashes when multiple images are compressed in a loop

When calling FlutterImageCompress.compressWithFile() within a 'for loop' multiple times, iOS crashes with:

Lost connection to device. Exited (sigterm)

A quick hack to solve this is by pausing (example in the code below) a short time just before compressing, but I'd like a more robust solution. I can confirm that this issue does not affect android. Calling the following code below on iOS with a List of 1 single element does not cause a crash. The ideal solution would be a native function compressWithFiles that accepts a List<String> paths and compresses multiples images in one call.

    List<List<int>> result = [];
    for (int i = 0; i < entityAssets.length; i++) {
      File file = await entityAssets[i].file;

      /// uncomment this to avoid crash on iOS
      /// await Future<Null>.delayed(Duration(milliseconds: 300));
      List<int> compressed = await FlutterImageCompress.compressWithFile(
          file.path,
          rotate: 90,
          minHeight: 1000,
          minWidth: 1000,
          quality: 95);

      result.add(compressed);
    }

WARNING: API 'variant.getPackageLibrary()' is obsolete

Hello, I am receiving this warning, is there anything I should do not to receive it?

WARNING: API 'variant.getPackageLibrary()' is obsolete and has been replaced with 'variant.getPackageLibraryProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
To determine what is calling variant.getPackageLibrary(), use -Pandroid.debug.obsoleteApi=true on the command line to display more information.
Affected Modules: flutter_image_compress

Transparent color is colored black on PNGs

When I compress a PNG image, the transparent area is replaced with black. So many of the PNG images are unusable, is it perhaps possible to leave it transparent or at least color it white?

I attached a sample image, compressed and not compressed.
before_compression
after_compression

Another breaking changes with latest Flutter upgrade

On the Dev and Master channels this week, looks like they changed the ImageStream handling of errors and reworked it a bit. I looked into it a little and see that you need to set up an ImageStreamListener now instead of the onError..
Here are the latest errors we're getting:

file:///D:/Program%20Files/Android/flutter/.pub-cache/git/flutter_image_compress-5a545f7e5409d091cd18f5891a8b07426f390729/lib/flutter_image_compress.dart:205:32: Error: No named parameter with the name 'onError'.
  stream.addListener(listener, onError: errorListener);
                               ^^^^^^^
file:///D:/Program%20Files/Android/flutter/.pub-cache/git/flutter_image_compress-5a545f7e5409d091cd18f5891a8b07426f390729/lib/flutter_image_compress.dart:207:27: Error: The argument type 'void Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///D:/Program%20Files/Android/flutter/packages/flutter/lib/src/painting/image_stream.dart').      
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///D:/Program%20Files/Android/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
    stream.removeListener(listener);

Here's the change discussions that should help in fixing it: flutter/flutter#32935 but wasn't finding many code examples..
I played around with it a little to see if I could figure it out, and got rid of the void listener() and ended up with something like this on line 205:

  //stream.addListener(listener, onError: errorListener);
  ImageStreamListener listener = ImageStreamListener((ImageInfo image, bool sync) {
    completer.complete(image);
  }, onError: errorListener);
  stream.addListener(listener);
  completer.future.then((ImageInfo info) {
    stream.removeListener(listener);
  });

Not saying this is it, I didn't want to put too much time with it, but would be nice to get it building again, so I wanted to help speed up the upgrade pains if I could...

Does not work on Isolate

Caught error: Exception: error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
flutter: =====>#0 Window.sendPlatformMessage (dart:ui/window.dart:811:9)
#1 BinaryMessages._sendPlatformMessage (package:flutter/src/services/platform_messages.dart:39:15)
#2 BinaryMessages.send (package:flutter/src/services/platform_messages.dart:87:12)
#3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:286:49)

#4 FlutterImageCompress.compressWithFile (package:flutter_image_compress/flutter_image_compress.dart:58:35)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.