Issue
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
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];
}
Answered By - Webkraft Studios Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.