Home > Software engineering >  how to validate Image size while picking/selecting the image in flutter?
how to validate Image size while picking/selecting the image in flutter?

Time:01-25

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.

CodePudding user response:

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 
         }
  }
  • Related