PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 5, 2022

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

 May 05, 2022     dart, filesize, flutter, image, plugins     No comments   

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.

1

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing