5

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.

Abbas Jafari
  • 1,492
  • 2
  • 16
  • 28

5 Answers5

20

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;
iDecode
  • 22,623
  • 19
  • 99
  • 186
12

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];
}
Webkraft Studios
  • 492
  • 5
  • 18
3
var file = File('the_path_to_the_image.jpg');
print(file.lengthSync()); 
iDecode
  • 22,623
  • 19
  • 99
  • 186
Ashok
  • 3,190
  • 15
  • 31
1

use this library https://pub.dev/packages/filesize

final bytes = image.readAsBytesSync().lengthInBytes;
final fs = filesize(bytes); // filesize method available inside package
  print(fs);
adarsh
  • 403
  • 3
  • 8
1

for getting file size in bytes size = await image.readAsBytes() or size = image.readAsBytesSync() then you can put this method in your utils class or something like that to get the Size Unit Dynamically

static String formatFileSize(size) {
    String hrSize = "";

    double b = size;
    double k = size/1024.0;
    double m = ((size/1024.0)/1024.0);
    double g = (((size/1024.0)/1024.0)/1024.0);
    double t = ((((size/1024.0)/1024.0)/1024.0)/1024.0);



    if ( t>1 ) {
      hrSize = t.toStringAsFixed(2) + " TB";
    } else if ( g>1 ) {
      hrSize = g.toStringAsFixed(2) + " GB";
    } else if ( m>1 ) {
      hrSize = m.toStringAsFixed(2) + " MB";
    } else if ( k>1 ) {
      hrSize = k.toStringAsFixed(2) + " KB";
    } else {
      hrSize = b.toStringAsFixed(2) +  " Bytes";
    }

try it

i used to use it for a while thanks to https://stackoverflow.com/a/20556766/15756879

Mohamed Shawky
  • 159
  • 2
  • 4