How to compress/reduce image sizes while uploading in Dart? I am trying to upload a 5MB image but I want to reduce its size while uploading. I am using Dart and Flutter.
There is an image manipulation package on pub. It even includes an example for exactly what you want to do.
import 'dart:io' as Io;
import 'package:image/image.dart';
void main() {
// Read an image from file (webp in this case).
// decodeImage will identify the format of the image and use the appropriate
// decoder.
Image image = decodeImage(new Io.File('test.webp').readAsBytesSync());
// Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
Image thumbnail = copyResize(image, 120);
// Save the thumbnail as a PNG.
new Io.File('thumbnail.png')
..writeAsBytesSync(encodePng(thumbnail));
}
For Dart
Use Image package:
With this package , you can load an image, resize it, and save it as a png:
First, add image
as a dependency in your pubspec.yaml file.
Usage :
import 'dart:io';
import 'package:image/image.dart';
void main() {
// Read an image from file (webp in this case).
// decodeImage will identify the format of the image and use the appropriate
// decoder.
Image image = decodeImage(File('test.webp').readAsBytesSync());
// Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
Image thumbnail = copyResize(image, width: 120);
// Save the thumbnail as a PNG.
File('thumbnail.png')..writeAsBytesSync(encodePng(thumbnail));
}
Don't use it if you would like to use this image in flutter . Use other solutions like flutter_image_compress or ResizeImage class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With