How to get the size of an image in Android?
Asked Answered
I

5

15

I'm able to get the height and width of an image. But is there a method to retrieve the size (in bytes or kb or mb) for an image stored in the phone?

Ison answered 16/2, 2012 at 18:31 Comment(3)
File file=new File(Environment.getExternalStorageDirectory(), "image.file"); long length = file.length();Shackleford
Before this, how you were getting the height and width of the image?Halbert
https://mcmap.net/q/459172/-how-to-get-the-height-and-width-of-an-imageview-bitmap-in-androidIson
I
33

Thank you for your answers. This is how I finally resolved it:

 Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), 
            R.drawable.ic_launcher);


     Bitmap bitmap = bitmapOrg;
     ByteArrayOutputStream stream = new ByteArrayOutputStream();   
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);   
     byte[] imageInByte = stream.toByteArray(); 
     long lengthbmp = imageInByte.length; 

Appreciate your time and answers :)

Ison answered 20/2, 2012 at 21:43 Comment(3)
Goon Answer. lengthbmp is in byte. lengthbmp/1024.0 is in KB. lengthbmp/1024.0/1024.0 is in MB.Druggist
How to get before compress and after compress?Jerald
Before compressing you can use bitmap.getByteCount(). Bear in mind that the "compressed" version is a JPEG, so if you compare both sizes you're not necessarily comparing apples to apples.Unseal
E
11

You just need to create a new File object such as...

String filepath = Environment.getExternalStorageDirectory() + "/file.png";
File file = new File(filepath);
long length = file.length();
Entwistle answered 16/2, 2012 at 18:40 Comment(1)
this gives the size of the file, not the image.Circumcise
C
10

Assuming your talking about a bitmap (and NOT an ImageView), there is a method Bitmap.getByteCount().

Carousal answered 16/2, 2012 at 18:39 Comment(2)
@mehmet Yes, but as of two years ago, when this was posted, it worked. I'll update when I get a chance.Carousal
use android.support.v4.graphics.BitmapCompat#getAllocationByteCount for compatibility.Circumcise
B
7
 File file = new File("/sdcard/imageName.jpeg");
 long length = file.length();
 length = length/1024;
 System.out.println("File Path : " + file.getPath() + ", File size : " + length +" KB");
Besought answered 2/9, 2015 at 6:54 Comment(0)
G
4

This returns the true size that is match in computers when you see file details with right click.

File file = new File("/sdcard/my_video.mp4");
long length = file.length() / 1024; // Size in KB
Gesticulatory answered 15/12, 2014 at 21:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.