0

I have seen the following code elsewhere for calculating the size in kb of an Android Bitmap, and was wondering if this is actually destructive to the Bitmap?

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

Specifically the line:

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

Does this actually mutate the Bitmap? Ideally I am looking for a totally non-destructive way of recording the image size in kb before continuing to use it.


NOTE: It is not practical in this case to use something like:
File file = new File(filepath);
long length = file.length();

Because I don't have the Bitmap on file at that point.


EDIT: I decided to solve my problem by getting the bytes downloaded value a different way: I extended InputStream and overrode the read(byte b[], int off, int len) method to include a counter, which can be returned at completion of the download - or indeed if the download was interrupted at all.
HomerPlata
  • 1,687
  • 5
  • 22
  • 39

1 Answers1

2

That's a horrible way of doing it. You're compressing the file in memory, writing that entire memory to a byte array, and getting the size of that- a total memory usage of 2-3x what the bitmap should take, with the side negative of being very slow.

Do you want the size of the bitmap loaded into memory or saved to disk? If you want it on disk, save it to disk then use the File api. Because if you aren't going to write it to disk anyway, why would you care what its size on disk is? If you want it in memory use bitmap.getByteCount()- which will always be higher than what your code returns, as its the size of the uncompressed bitmap.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • I know it's a horrible way, you're right. I found this code in multiple locations and thought that maybe only horrible ways existed. Can't believe I overlooked getByteCount(). Does this accurately reflect the kb that have been downloaded? I'm looking to keep track of mobile data usage. – HomerPlata Mar 30 '17 at 20:21
  • So there's compressed and uncompressed bitmaps. When in memory, bitmaps are uncompressed and that's what getByteCount returns. When on disk or sent over the network, they're generally compressed. Which is closer (but not exactly because you aren't necessarily using the same compression algorithm and quality setting) to your code. But if you want to track bandwidth, check out http://stackoverflow.com/questions/11939939/how-can-i-find-the-data-usage-on-a-per-application-basis-on-android for APIs to do so more directly. – Gabe Sechan Mar 30 '17 at 20:26
  • Thank you sir :-) – HomerPlata Mar 30 '17 at 20:36