Home > Back-end >  How to compress Image using image_picker - Flutter
How to compress Image using image_picker - Flutter

Time:05-06

I'm building an image compressor. For that, I'm using the flutter image_picker package, it has a property called imageQuality which let you reduce the size of the image.

What I'm trying to achieve is that first upload the image through imagePicker and then compress it. So I can get both original and compressed sizes (before and after).

Currently what it does is compress the size while uploading/picking the image. That's what I do not want. How can I break into two steps (first upload and then compress the size using image quality parameter)

  void selectImage() async {
    final imagePicker = await ImagePicker().pickImage(source: ImageSource.gallery, imageQuality: 80); // upload and compress (I want to split this process)
    photoSize = await getFileSize(imagePicker!.path, 1);
    setState(() {
      _file = File(imagePicker.path);
    });
  }

CodePudding user response:

Based on your question why don't you use Image_compression_flutter to compress image after you have selected the image with imageQuality: 100 .

By using another compression function , you can compress the image and get the compressed image as output.

CodePudding user response:

Please find the below code

You can check this link for the complete example code.

You can try compressing the image using the following function.

Please refer to the below plugins for compressing image

flutter_image_compress: ^0.7.0

Future<File> compressImage(File file) async {
    final filePath = file.absolute.path;
    final lastIndex = filePath.lastIndexOf(new RegExp(r'.png|.jp'));
    final splitted = filePath.substring(0, (lastIndex));
    final outPath = "${splitted}_out${filePath.substring(lastIndex)}";

    if (lastIndex == filePath.lastIndexOf(new RegExp(r'.png'))) {
      final compressedImage = await FlutterImageCompress.compressAndGetFile(
          filePath, outPath,
          minWidth: 1000,
          minHeight: 1000,
          quality: 50,
          format: CompressFormat.png);
      return compressedImage;
    } else {
      final compressedImage = await FlutterImageCompress.compressAndGetFile(
        filePath,
        outPath,
        minWidth: 1000,
        minHeight: 1000,
        quality: 50,
      );
      return compressedImage;
    }
  }

 File photoCompressedFile =
            await compressImage(File(pickedImage.path));
        print("Path of Compressed File: ${photoCompressedFile.path}");
  • Related