flutterimagepicker

How to set maximum size of image from image Picker in Flutter


this is my code

chooseImage() async {
    XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
    imagePath = await pickedFile!.readAsBytes();  
}

Solution

  • If you want to completely block files over a certain size, you can check the size of the file using it's length property, and handle the result accordingly

    chooseImage() async {
        var maxFileSizeInBytes = 2 * 1048576; // 2MB (You'll probably want this outside of this function so you can reuse the value elsewhere)
    
        XFile? pickedFile = await ImagePicker().pickImage(
          source: ImageSource.gallery,
        );
        var imagePath = await pickedFile!.readAsBytes();
    
        var fileSize = imagePath.length; // Get the file size in bytes
        if (fileSize <= maxFileSizeInBytes) {
            // File is the right size, upload/use it
        } else {
            // File is too large, ask user to upload a smaller file, or compress the file/image
        }
    }