skip to Main Content

I am trying to get the image size in MB but the printed result is less than the actual result when see the size in phone gallery why?

for example image size is 5MB when uploaded it from flutter it print 2.4MB

here is my code:

pickerFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
 int fileSizeInBytes = await pickerFile!.length();
 double fileSizeInKB = fileSizeInBytes / 1024;
 double fileSizeInMB = fileSizeInKB / 1024;

2

Answers


  1. The size displayed in a phone gallery might differ from the size calculated programmatically due to various factors such as compression, metadata, or the way the image is rendered on the screen.

    Login or Signup to reply.
  2. You can try this below ways

    1. Please try using imageQuality: 50 like this

      ImagePicker().pickImage(

      source: ImageSource.gallery,

      imageQuality: 50,
      // adjust this as per your need

      );

    2. You can also define like this

      var maxFileSizeInBytes = 2 * 1048576; // 2MB

      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
      

      }
      }

    3. You can use this package and try image: ^4.1.7

    4. Please Check the file length using readasbytes like this:

      final bytes = image.readAsBytesSync().lengthInBytes;

      final kb = bytes / 1024;

      final mb = kb / 1024;

    Hope you will find your answer from one of the above steps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search