0

Here's the code to pick up the image from the gallary.

Future getImage() async {
    var image = await ImagePicker().getImage(source: ImageSource.gallery);
     getImageSize();
    // imageQuality: 50;
    setState(() {
      selectedImage = File(image!.path);
    });
  }

code to get the size of the selected image.

double getImageSize(File selectedImage) {
    final bytes = selectedImage.readAsBytesSync().lengthInBytes;
    final kb = bytes / 1024;
    final mb = kb / 1024;
    if (kb < 5000.0) {
      print("Image is Less than 5MB");
    } else {
      print("Image is More than 5MB...!!!");
    }
    return kb;
  }

So, after the selecting the image and checking up if the image is less than 5mb it should return the "kb" and if the image size is more than "5mb" then the function should display the error message in the SnackBar.

  • I would leave the function as it is, since you can use it in other places as well. I would perhaps take out the prints there. You can simply check the return value to see if it is greater than 5000, and if it is, call a snack bar. – Ozan Taskiran Jan 23 '23 at 16:32
  • You will get the size of the image from getImageSize() Function and then you have to put a condition for size like, if(Size > 1MB or 1024KB) You can get MB when you divide kb / 1024. getImageSize() function returns a value in KB after that you can change it to MB or directly return MB from the function and check the image size. – Chirag Rathod Jan 23 '23 at 16:34

1 Answers1

0

you can do it like this

 XFile? imageFile = await ImagePicker().pickImage(source: ImageSource.camera);
 if (imageFile != null) {
      final decodedImage = await decodeImageFromList(await imageFile.readAsBytes());
    if (decodedImage.height > 255 && decodedImage.width > 255) {
        //do your validation here 
         }
  }
Munsif Ali
  • 1,839
  • 1
  • 8
  • 22