Created
May 8, 2021 01:29
-
-
Save WahdanZ/39256be974279aaaeae408639ba78651 to your computer and use it in GitHub Desktop.
compres image flutter dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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