简体   繁体   中英

How to display the image file size taken from Flutter image_picker plugin?

I am creating a Flutter app and I want to show the image file size (in kb/mb) when the user gets an image from either the gallery or camera.

1

Right now, when the user gets an image, it displays a thumbnail and text "Image Selected" on the screen, as shown in the picture. I want it to also display the image file size under "Image Selected".

File _image;
final picker = ImagePicker();

Future getImageFromCamera() async {
  final pickedImage = await picker.getImage(source: ImageSource.camera);

  setState(() {
    if (pickedImage != null) {
      _image = File(pickedImage.path);
    } else {
      print('No image selected.');
    }
  });
}

Future getImageFromGallery() async {
  final pickedImage = await picker.getImage(source: ImageSource.gallery);

  setState(() {
    if (pickedImage != null) {
      _image = File(pickedImage.path);
    } else {
      print('No image selected.');
    }
  });
}

Here is a solution using a function that will provide you with the file size as a neat formatted string.

Imports:

import 'dart:io';
import 'dart:math';

Output:

//if(await _image.exists())
print(getFilesizeString(bytes: _image.lengthSync()));
// Output Example: 17 Bytes, 30MB, 7GB

Function:

// Format File Size
static String getFileSizeString({@required int bytes, int decimals = 0}) {
  if (bytes <= 0) return "0 Bytes";
  const suffixes = [" Bytes", "KB", "MB", "GB", "TB"];
  var i = (log(bytes) / log(1024)).floor();
  return ((bytes / pow(1024, i)).toStringAsFixed(decimals)) + suffixes[i];
}

Use length orlengthSync to get the size of the file. length or lengthSync would return the size in bytes, you need to convert it to kilo-bytes or mega-bytes.

Check the file length using readasbytes;

//final bytes = (await image.readAsBytes()).lengthInBytes;
final bytes = image.readAsBytesSync().lengthInBytes;
final kb = bytes / 1024;
final mb = kb / 1024;

For Image picker

Future getImageSize() async {
 final pickedImage = await picker.getImage(source: ImageSource.gallery);
 final bytes = pickedImage.readAsBytesSync().lengthInBytes;
 final kb = bytes / 1024;
  final mb = kb / 1024;
 setState(() {
  if (pickedImage != null) {
   var _image = File(pickedImage.path);
   } else {
   print('No image selected.');
   }
   });}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM