Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress/reduce image sizes while uploading in Dart?

Tags:

flutter

dart

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.

like image 443
Amit Wani Avatar asked May 26 '18 13:05

Amit Wani


2 Answers

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));
}
like image 165
ABabin Avatar answered Sep 29 '22 13:09

ABabin


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.

like image 35
Kabirou Agouda Avatar answered Sep 29 '22 14:09

Kabirou Agouda