Saturday, June 7, 2014

Avoiding Out of Memory errors while loading large bitmaps

Hi everyone! Has been a long time since I wrote here, and it is time to clean the dust and publish new and hopefully useful stuff :)
Today I will present some suggestion on how to minimize the amount of RAM while loading large bitmap on Android, in order to avoid the common OutOfMemory error.

New mobile phones and tablets have constantly seen their display to become more capable in term of display resolution. This brings many positive aspects, but for developers, usually a lot of headaches: more capable displays means much more memory required to display images and pictures on them.

An image (a PNG, a JPEG..) is always displayed as a matrix of pixels. Supposing a 32 bit depth color, each pixel is represented as 32 bits, i.e. 4 bytes (R,G,B and alpha component).
On a modern display (for example, let's take the Nexus 5), we have 1080x1920 pixels. Potentially, an app that shows an image fullscreen (for simplicity we pretend the black bar with status bar and Android system buttons is hidden) must load in memory a bitmap: 4 * 1080 * 1920 = 8294400 bytes big.

This would not be a problem if the only thing loaded in the current instance of dalvik VM is that image, but of course in memory we can have much more objects.

How much memory does Android borrow to a single app? It depends. Each Android device might in theory have a different threshold which dictates how much memory is granted to the application. It is declared as a system property and can be read by typing this on the console:

adb pull /system/build.prop
cat build.prop

and checking the property dalvik.vm.heapgrowthlimit 
In general, devices with bigger dpi screens have a higher value of heap limit. For example, the LG Nexus 5, a XXHDPI device, has 192MB of limit. As said, device with the same resolution might have different heap limit: an HTC One X (XHDPI device) has 92MB of limit; a Samsung S3 (also XHDPI) has only 64MB of heap limit.

An app can request more RAM, by declaring the android:largeHeap property in the Android manifest. How much RAM can be granted? Also this property is defined in the same file (dalvik.vm.heapsize), and in case of my Nexus 5, is 512 MB.
Why not just using always this property? Because the GC tends to become inefficient and app will be much slower. 

Consequently, in mostly all cases, instead of setting this attribute we need to minimize the amount of RAM needed, especially if we want to tackle the well known OutOfMemory exception.

In order to minimize the possibility of such error, a well-behaving app that need to load a large bitmap must:
- check the amount of free memory left 
- adopt strategies in case the available memory is not enough to load it.

Check the amount of free memory left

Android inherits the Runtime clas sfrom Java standard library. This helps getting the information we fetched via console: in particular, how much memory is available, how much free memory is left before the VM will complain.

In the gist above, I calculate the total available heap (192MB on my device) and the available heap (it was around 175MB before loading the bitmap).

Check how big is the bitmap we want to load

On Android3.0+, we can use a handy class called BitmapFactory.Options. It does a lot of useful things, one of which is giving info about the image, without loading it in memory.

In the snippet above, I use the aforementioned class to calculate image width and height without loading it in RAM, by setting to true the inJustDecodeBounds property. We can have a rough aestimate of how large will be the image in RAM from its width, height attributes.

Load a subscaled version of the bitmap in RAM

If the memory available is less than the amount of memory required by the bitmap, then we apply some subsampling. The image will be imperceptibly lower in quality on the specific device where this subsampling will happen, but we will avoid the Out of Memory error. User will be happy and probably won't even notice the difference.
Again, to subsample the image we use the BitmapFactory.Options:

We use power of 2 because the decoder will anyway round other values to a power of 2. Also, I placed a limit o 8 but also this can be avoided and image can be subsampled at any level.

By subsampling an image with a factor of 2 you can see you will be able to spare almost 75% of memory, and the difference in quality is almost negligible.

You can download the sample app which contains all these snippets and a demo activity you can play with here: https://github.com/nalitzis/TestMemoryViews

57 comments:

  1. Your posts is really helpful for me.Thanks for your wonderful post. I am very happy to read your post. Phonegap training in chennai | Phonegap training chennai | Phonegap course in chennai | Phonegap course chennai

    ReplyDelete
  2. hi body! as I know , the amount of free memory left is alway not accurate and unstable, had you ever try this in develop? I doubt that it is ever work?

    ReplyDelete
  3. The information you have given here are most worthy for me. I have implemented in my training program as well, thanks for sharing.

    Hadoop Training Chennai
    Hadoop Training in Chennai

    ReplyDelete
  4. I have read your blog, it was good to read & I am getting some useful info's through your blog keep sharing... Informatica is an ETL tools helps to transform your old business leads into new vision. Learn Informatica training in chennaifrom corporate professionals with very good experience in informatica tool.
    Regards,
    Best Informatica Training In Chennai|Informatica training center in Chennai

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to Selenium Training in Chennai reach Greens Technology training and placement academy.
    selenium Training in Chennai

    ReplyDelete
  8. This is a great post, very interesting points and I have enjoyed immeasurably. thanks!
    SEO services Melbourne | Magento Development Company

    ReplyDelete
  9. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for developing their skill to get good career.
    Regards,
    SAP training in chennai|SAP course in chennai|SAP Training in Chennai|sap course in Chennai

    ReplyDelete
  10. The article you have shared is impressive and I am glad to read this posting. Thank you so much for sharing it
    website design Melbourne | custom website design services |SEO services Melbourne | SMO services Melbourne

    ReplyDelete
  11. Appreciated work. I like this post a lot. I hope it will be helpful for all of the readers.Keep it up..
    custom web development Melbourne | Magento Development Company | mobile application development melbourne | ipad application development melbourne

    ReplyDelete
  12. Awesome Post!!! With unique content, I really get reading interest when I am following your article, I hope I ll help many of them who looking this pretty information.
    Regards,

    ccna course in Chennai|ccna training in Chennai

    ReplyDelete
  13. Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    qtp training in chennai

    ReplyDelete
  14. All of these tips are great, that’s very interesting. I’m so tempted to try that myself, but you would think if it were effective, more people would do it.

    iOS training in chennai

    ReplyDelete

  15. We share it this site's information very advantages. I thinking many interesting here.


    This information is impressive; I am inspired by your post writing style & how continuously you describe this topic.
    Java Training in Chennai
    Java Training Institute in Chennai

    ReplyDelete

  16. Incredible post. Articles that have significant and savvy remarks are more agreeable, at any rate to me. It’s fascinating to peruse what other individuals thought and how it identifies with them or their customers, as their point of view could help you later on.

    PSD to Wordpress
    wordpress website development

    ReplyDelete
  17. Its really nice article and informative.Thanks for sharing this article.
    iOS Training In Chennai | iOS Training Institute In Chennai

    ReplyDelete
  18. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    MEAN stack training in annanagar
    MEAN stack training in Velachery
    MEAN stack training Sholinganallur

    ReplyDelete
  19. Nice it seems to be good post... It will get readers engagement on the article since readers engagement plays an vital role in every blog.i am expecting more updated posts from your hands.
    Sap Pm Training From India

    Sap Mm Training From India

    Sap Sd Training From India

    ReplyDelete
  20. I think this is the best article today about the future technology. Thanks for taking your own time to discuss this topic, I feel happy about that curiosity has increased to learn more about this topic. Keep sharing your information regularly for my future reference.
    Selenium Training in Chennai
    software testing selenium training
    JAVA J2EE Training Institutes in Chennai
    JAVA Course
    iOS Training in Adyar
    iOS Course in Tambaram

    ReplyDelete
  21. Awwsome informative blog ,Very good information thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.
    Aviation Academy in Chennai | Aviation Courses in Chennai | Best Aviation Academy in Chennai | Aviation Institute in Chennai | Aviation Training in Chennai

    ReplyDelete
  22. Nice post. I learned some new information. Thanks for sharing.

    Technology

    redbeardpress

    ReplyDelete
  23. Nice idea,keep sharing your ideas with us.i hope this information's will be helpful for the new learners.
    Java Training in Sholinganallur
    Java Training in T nagar
    Java Training in Anna nagar
    Java Training in Bangalore

    ReplyDelete
  24. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's. Machine learning training in chennai
    python machine learning training in chennai

    ReplyDelete
  25. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.| Roles and reponsibilities of hadoop developer | hadoop developer skills Set | hadoop training course fees in chennai | Hadoop Training in Chennai Omr

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. Vanskeligheter( van bi ) vil passere. På samme måte som( van điện từ ) regnet utenfor( van giảm áp ) vinduet, hvor nostalgisk( van xả khí ) er det som til slutt( van cửa ) vil fjerne( van công nghiệp ) himmelen.

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. Images in PNG format are also a great thing for bitmaps. People can convert jpg to supplier png: https://jpg4png.com/ for the most practical experience

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete

  31. click here formore info.
    ............................................................

    ReplyDelete
  32. Really i am Enjoy Reading all the Articles...Thanks for Such an Interesting Information's and waiting to read many more Articles like this and visit below for more...
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  33. Truly welcome this magnificent post that you have accommodated us. Great site and an incredible theme to I truly get astonished to understand this. It's great. Thank you! startup web design

    ReplyDelete
  34. I am really enjoying reading your well written articles. It’s hard to come by experienced people about this subject, but you seem like you know what you’re talking about! Thanks.
    Java Training in Chennai

    Java Training in Velachery

    Java Training inTambaram

    Java Training in Porur

    Java Training in Omr

    Java Training in Annanagar

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  37. Here is the best Software training institute to study AWS training in Chennai, from Infycle Technologies and we come up with courses like Cyber Security, Graphic Design and Animation, Block Security, Java, Cyber Security, Oracle, Python, Big data, Azure, Python, Manual and Automation Testing, DevOps, Medical Coding etc., with outstanding training with experienced trainers and a friendly environment with 100+ Live Practical Sessions and Real-Time scenarios. After completion of the course a student will be able to obtain more knowledge of the course and be able to crack interviews on top MNC’s. For more queries dial 7504633633 or 7502633633.


    ReplyDelete
  38. Excellent Post,Thanks for sharing really interesting and informative content. with some great tool recommendation.
    we are the Top Web Development Company in Bangalore

    ReplyDelete
  39. This comment has been removed by the author.

    ReplyDelete