1

I have successfully implemented flutter multi image picker. But I want to reduce its quality. I have seen threads where its been said to use flutter_Image_compress library. But I can't seem to understand that how to implement it with multi image picker.

Multi Image picker

Future<List<Asset>> loadAssets() async {
List<Asset> resultList = List<Asset>();
String error = "No error Detected";

try {
  resultList = await MultiImagePicker.pickImages(
    maxImages: 10,
    enableCamera: true,
    selectedAssets: images,
    cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
    materialOptions: MaterialOptions(
      actionBarColor: "#abcdef",
      actionBarTitle: "Upload Image",
      allViewTitle: "All Photos",
      useDetailsView: false,
      selectCircleStrokeColor: "#000000",
    ),
  );

  showInSnackBar("loading images");
  print(resultList.length);
  print((await resultList[0].getThumbByteData(122, 100)));
  print((await resultList[0].getByteData()));
  print((await resultList[0].metadata));
  print("loadAssets is called");

} on Exception catch (e) {
  error = e.toString();
  print(error);
}



if (!mounted){
  print("Not mounted");
}
else {
  setState(() {
    images = resultList;
    _error = error;
  });
}

return images;

}

Flutter image compress

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

    final compressedImage = await FlutterImageCompress.compressAndGetFile(
        filePath,
        outPath,
        minWidth: 1000,
        minHeight: 1000,
        quality: 70);
  }

This is what i did

Future<List<Asset>> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    List<File> fileImageArray=[];
    String error = "No error Detected";

    try {

      resultList = await MultiImagePicker.pickImages(
        maxImages: 10,
        enableCamera: true,
        selectedAssets: images,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Upload Image",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),

      );
      resultList.forEach((imageAsset) async {
        final filePath = await FlutterAbsolutePath.getAbsolutePath(imageAsset.identifier);

        File tempFile = File(filePath);
        if (tempFile.existsSync()) {
          fileImageArray.add(tempFile);
        }
      });
compressImage(fileImageArray);

      showInSnackBar("loading images");
      print(resultList.length);
      print((await resultList[0].getThumbByteData(122, 100)));
      print((await resultList[0].getByteData()));
      print((await resultList[0].metadata));
      print("loadAssets is called");

    } on Exception catch (e) {
      error = e.toString();
      print(error);
    }
    if (!mounted){
      print("Not mounted");
    }
    else {
      setState(() {
        print('Presed1');
        images = resultList;
        _error = error;
      });
    }

    return images;
  }

  void compressImage(fileImageArray) async {
    for(var i in fileImageArray){
      final filePath = i.absolute.path;
      final lastIndex = i.lastIndexOf(new RegExp(r'.jp'));
      final splitted = i.substring(0, (lastIndex));
      final outPath = "${splitted}_out${filePath.substring(lastIndex)}";

      final compressedImage = await FlutterImageCompress.compressAndGetFile(
          filePath,
          outPath,
          minWidth: 240,
          minHeight: 240,
          quality: 5);
      setState(() {
   print('pressed2');
        fileImageArray= compressedImage;
      });
    }

}

onPressed: () async {
                        List<Asset> asst = await loadAssets();
                        if (asst.length == 0) {
                          showAlert("No images selected");
                        }
                        SizedBox(height: 10,);

                        showInSnackBar('Images Successfully loaded');
                        //                 SnackBar snackbar = SnackBar(content: Text('Please wait, we are uploading'));
                        //_scaffoldKey.currentState.showSnackBar(new SnackBar(content: new Text(value)));
                      }
19
  • first, take the image using multi image picker. then you need to convert asset to file. Commented Dec 12, 2020 at 17:21
  • Then provide that to your compressedImage function Commented Dec 12, 2020 at 17:22
  • please @AbhishekGhaskata check it now. I updated the code. It still isnt compressing image size. What am i doing wrong sir? Commented Dec 12, 2020 at 19:32
  • you have to iterate fileImageArray via for loop Commented Dec 13, 2020 at 7:44
  • @AbhishekGhaskata Bhai. Please kindly help me. Dont know how to iterate it :( Trying since yesterday :( Commented Dec 13, 2020 at 10:36

2 Answers 2

1

Please use this to convert List to List

List<File> fileImageArray=[];
...
resultList.forEach((imageAsset) async {
    final filePath = await FlutterAbsolutePath.getAbsolutePath(imageAsset.identifier);
    
    File tempFile = File(filePath);
    if (tempFile.existsSync()) {
        fileImageArray.add(tempFile);
    }
});

Give fileImageArray to compressImage method. and iterate it using for loop

 void compressImage(fileImageArray) async {
    for(var i in fileImageArray){
    final filePath = i.absolute.path;
    final lastIndex = i.lastIndexOf(new RegExp(r'.jp'));
    final splitted = i.substring(0, (lastIndex));
    final outPath = "${splitted}_out${filePath.substring(lastIndex)}";

    final compressedImage = await FlutterImageCompress.compressAndGetFile(
        filePath,
        outPath,
        minWidth: 240,
        minHeight: 240,
        quality: 5);
    setState(() {
      fileImageArray= compressedImage;
    });
   }
  }
Sign up to request clarification or add additional context in comments.

3 Comments

First, you have to convert List<Asset> to List<File> then provide to compressImage method
can u pls tell me what should be srcPath and the target path if i upload my all files to firebase?
Here there is very good docs from firebase firebase.flutter.dev/docs/storage/usage which might helps you
0

Flutter Absolute Path is not in development anymore and is not updated with the android v2 embedding. Hence I suggest to use path_provider in the below to transform an Asset to File and compress:

import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:path_provider/path_provider.dart';

Future<File> compressAndUploadAssetImage(Asset asset, Reference ref) async {
        final byteData = await asset.getByteData();
        final tempFile = File("${(await getTemporaryDirectory()).path}/${asset.name}");
        final file = await tempFile.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes),);
        File compressedFile = await FlutterNativeImage.compressImage(file.path, quality: 70);
        return compressedFile;

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.