I have a Bitmap
and I want to get the size of the bitmap in KB, MB or etc
TRID NUMBER 1 - so I tried this but it is returning the wrong output because I have an image whose size is 42.57 KB but in the result, it is returning 128 B
// originalBitmap is global var
ByteArrayOutputStream stream = new ByteArrayOutputStream();
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long bitmap_size = imageInByte.length / 1024;
Log.d(TAG, "size of bitmap - "+Formatter.formatShortFileSize(this,bitmap_size));
TRID NUMBER 2 - so In this tried is simply done this thing but it is also showing wrong output it showing 1.2 MB of that same image whose size is 42.57 KB
Log.d(TAG, "Image size : "+Formatter.formatShortFileSize(this, originalBitmap.getByteCount()));
NOTE: I have no real device so tested this in the emulator. may this cause or what do you think
any help will be appreciated. thank you.
Don't divide by 1024
long bitmap_size = imageInByte.length / 1024;
If you are using Formatter.formatShortFileSize then just use the original length of the byte array.
This code is compressing the image with this:
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
How do you know the size of the image after this compression? You might write the compressed image out to a file, however the imageInByte.length
has to be the number of bytes in the byte array. Are you sure it is NOT this size?
You said " I have an image whose size is 42.57 KB " and I suppose it isn't a real Bitmap but some JPEG, PNG, WEBP or other image format. If you import this image in Java using BitmapFactory the decoder "expands" compressed image bytes in a real Bitmap made by Width x Height x 3 (or "4" if apha is supported from original image format). So a simple 1Kb image of 100x100 PNG file could became 100x100*3 = 30000 = 30Kb in Java when " Bitmap.getByteCount() " is executed. Compressing (again) this 30Kb Bitmap in a different or similar format could generate a different output so a different final length.
Maybe you need some explanation:
So you're Compressing a Bitmap to get a compressed JPEG and then you're getting JPEG length (header included). Obliviously a compressed file is normally smaller than original one.
Comparing a Compressed or not-Compressed Java output with original Image File is 99% of times "wrong" because re-compressing a decompressed image file usually results in a different result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.