Huge spike in memory consumption when using png wi

2020-04-21 02:13发布

问题:

I am using a button with a png background for CopyToClipboard function in my app (used about 6-7 times in various fragment). Since the image should be small for my purpose, I increased the area of my image by putting in extra transparent area around the image so that I could increase the button size for clickable area but keep the image small (I know its not efficient and since then I have devised better way to achieve this).

I noticed the huge spikes later on afterwards when uploading some other images (big images about 150kb size), and after a lot of debugging (and I do mean a lot!) I found that the problem was not due to the bigger images but due to the CopyToClipboard image which was of just 8kb in size!!! Changing back to older CopyToClipboard image (having lesser Transparent area) brought the memory consumption back to normal.

My question is why did that happen? For such a small image to create such huge spikes (more than doubled the memory consumption from previous) and made the app slow, is quite baffling.

Image shown below : The White area is the transparent area. My button dimension : 15dp x 15dp .

I repeat, My question is why did that happen? Not a solution for it since I already solved the problem.

回答1:

It doesn't really matter that your image is only 7-8KB on disk, because it will take much more memory when it's decoded.

Apparently, large transparent area can be efficiently encoded in PNG file, so the image has that small size. But in fact, it's dimension is (600 x 745), so in memory it will take roughly (600 * 745 * 4) bytes, plus some meta information, so nearly 2 megabytes. 4 multiplier stands for an amount of bytes needed to encode color with alpha channel. Android Bitmaps are represented internally by linear one-dimensional array of integers, so you can imagine that system needs to allocate an array with size 600 * 745 = 447000 to create your Bitmap.

That's why memory consumption is so high for such a simple image.