'Check image size( kb, mb...) in flutter?
I know how to check image width and height:
import 'dart:io';
File image = new File('image.png'); // Or any other way to get a File instance.
var decodedImage = await decodeImageFromList(image.readAsBytesSync());
print(decodedImage.width);
print(decodedImage.height)
But I want to check the image size like 100kb, 200kb, or something like that is there any way, please help me.
Solution 1:[1]
Use lengthInBytes.
final bytes = image.readAsBytesSync().lengthInBytes;
final kb = bytes / 1024;
final mb = kb / 1024;
If you want to async-await, use
final bytes = (await image.readAsBytes()).lengthInBytes;
Solution 2:[2]
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:
File image = new File('image.png');
print(getFilesizeString(bytes: image.lengthSync()}); // Output: 17kb, 30mb, 7gb
Function:
// Format File Size
static String getFileSizeString({@required int bytes, int decimals = 0}) {
const suffixes = ["b", "kb", "mb", "gb", "tb"];
var i = (log(bytes) / log(1024)).floor();
return ((bytes / pow(1024, i)).toStringAsFixed(decimals)) + suffixes[i];
}
Solution 3:[3]
var file = File('the_path_to_the_image.jpg');
print(file.lengthSync());
Solution 4:[4]
use this library https://pub.dev/packages/filesize
final bytes = image.readAsBytesSync().lengthInBytes;
final fs = filesize(bytes); // filesize method available inside package
print(fs);
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 | iDecode |
| Solution 2 | |
| Solution 3 | iDecode |
| Solution 4 |
