如何显示从 Flutter image_picker 插件获取的图像文件大小?

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

我正在创建一个 Flutter 应用程序,我想在用户从图库或相机获取图像时显示图像文件大小(在 kb/mb 中)。

1

现在,当用户获取图像时,它会在屏幕上显示缩略图和文本“已选择图像”,如图所示。我希望它也能在“所选图像”下显示图像文件大小。

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.');
    }
  });
}

使用length or lengthSync获取文件的大小。 length 或 lengthSync 将 return 以字节为单位的大小,您需要将其转换为千字节或兆字节。

使用readasbytes检查文件长度;

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

这是一个使用函数的解决方案,该函数将以整齐的格式字符串形式为您提供文件大小。

进口:

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

输出:

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

函数:

// 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];
}

对于图像选择器

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.');
   }
   });}