Skip to content

Instantly share code, notes, and snippets.

@WahdanZ
Created May 8, 2021 01:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WahdanZ/39256be974279aaaeae408639ba78651 to your computer and use it in GitHub Desktop.
Save WahdanZ/39256be974279aaaeae408639ba78651 to your computer and use it in GitHub Desktop.
compres image flutter dart
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:image/image.dart' as Im;
import 'package:path_provider/path_provider.dart' show getTemporaryDirectory;
Future<File> imageCompress(File file,{int maxFileSize = 3}) async {
Im.Image image = Im.decodeImage( file.readAsBytesSync());
Im.Image smallerImage = Im.copyResize(image, width: image.width ~/ 2);
final appPath = await getTemporaryDirectory();
file = File('${appPath.path}/img_c${DateTime.now().millisecondsSinceEpoch}.jpg')
..writeAsBytesSync(Im.encodeJpg(smallerImage, quality: 70));
if (file.fileSizeInMB >= maxFileSize) {
Im.Image smallerImage2 =
Im.copyResize(image, width: smallerImage.width ~/ 2);
file =File(
'${appPath.path}/img_c${DateTime.now().millisecondsSinceEpoch}c.jpg')
..writeAsBytesSync(Im.encodeJpg(smallerImage2, quality: 70));
}
return file;
}
extension FileExtension on File {
get fileSizeInKB {
if (kIsWeb) {
return this.length();
} else {
return this.lengthSync() / 1024;
}
}
String get name {
return this?.path?.split("/")?.last;
}
String get extType {
return this?.path?.split("/")?.last?.split(".")?.last?.toLowerCase();
}
get fileSizeInMB {
if (kIsWeb) {
this.length();
} else {
return fileSizeInKB / 1024;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment