'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.
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.');
}
});
}
Solution 1:[1]
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];
}
Solution 2:[2]
Use length or lengthSync 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.
Solution 3:[3]
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;
Solution 4:[4]
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.');
}
});}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Webkraft Studios |
| Solution 2 | Tirth Patel |
| Solution 3 | Muhtar |
| Solution 4 | Rohit Sainik |
