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

66 comments:

  1. Thanks for sharing informative article on java application development. Your post helped to understand the career in Java. JAVA Training in Chennai

    ReplyDelete
  2. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing. Android training in chennai | Android training chennai |Android course in chennai | Android course chennai

    ReplyDelete
  3. 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
  4. Hi there! I foresee that you will be a great blogger who will imprint on the growing online masses. All the best for your future. Your information is unique and clear. There is no unwavering words that distract readers like me. Way to go! FYI…checkout social media expert , bespoke eyecatching flyer design marketplaces. You can kickstart your career through these micro job sites. Looking forward to more of your blogs.

    ReplyDelete
  5. 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
  6. 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
  7. 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
  8. Oracle DBA Training in Chennai
    Thanks for sharing this informative blog. I did Oracle DBA Certification in Greens Technology at Adyar. This is really useful for me to make a bright career..

    ReplyDelete
  9. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Websphere Training in Chennai

    ReplyDelete
  10. Data warehousing Training in Chennai
    I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

    ReplyDelete
  11. Selenium Training in Chennai
    Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    ReplyDelete
  12. Oracle Training in chennai
    Thanks for sharing such a great information..Its really nice and informative..

    ReplyDelete
  13. SAP Training in Chennai
    This post is really nice and informative. The explanation given is really comprehensive and informative..

    ReplyDelete
  14. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..
    Android Training In Chennai In Chennai

    ReplyDelete
  15. Pretty article! I found some useful information in your blog, it was awesome to read,thanks for sharing this great content to my vision, keep sharing..
    Unix Training In Chennai

    ReplyDelete
  16. I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    SalesForce Training in Chennai

    ReplyDelete
  17. There are lots of information about latest technology and how to get trained in them, like Best Hadoop Training In Chennai in Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies Hadoop Training in Chennai By the way you are running a great blog. Thanks for sharing this blogs..

    ReplyDelete
  18. This is really an awesome article. Thank you for sharing this.It is worth reading for everyone. Visit us:
    Oracle Training in Chennai

    ReplyDelete
  19. This is really an awesome article. Thank you for sharing this.It is worth reading for everyone. Visit us:
    Oracle Training in Chennai

    ReplyDelete
  20. 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.
    Oracle DBA Training in Chennai

    ReplyDelete
  21. 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.
    Oracle DBA Training in Chennai

    ReplyDelete
  22. great article!!!!!This is very importent information for us.I like all content and information.I have read it.You know more about this please visit again.
    Oracle RAC Training in Chennai

    ReplyDelete
  23. great article!!!!!This is very importent information for us.I like all content and information.I have read it.You know more about this please visit again.
    Oracle RAC Training in Chennai

    ReplyDelete
  24. Wonderful tips, very helpful well explained. Your post is definitely incredible. I will refer this to my friend.
    SalesForce Training in Chennai

    ReplyDelete
  25. Wonderful tips, very helpful well explained. Your post is definitely incredible. I will refer this to my friend.
    SalesForce Training in Chennai

    ReplyDelete
  26. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Java Training in Chennai

    ReplyDelete
  27. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Java Training in Chennai

    ReplyDelete
  28. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    PHP Training in Chennai

    ReplyDelete
  29. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    PHP Training in Chennai

    ReplyDelete
  30. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me..
    Android Training in Chennai

    ReplyDelete
  31. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me..
    Android Training in Chennai

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

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

    ReplyDelete
  34. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    SAP Training in Chennai

    ReplyDelete
  35. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    SAP Training in Chennai

    ReplyDelete
  36. Excellent information with unique content and it is very useful to know about the information based on blogs.
    Hadoop Training in Chennai

    ReplyDelete
  37. Excellent information with unique content and it is very useful to know about the information based on blogs.
    Hadoop Training in Chennai

    ReplyDelete
  38. 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
  39. 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

  40. nice blogs.
    Friend chatMake new friend’s without revealing yourself. Dial 543216 at Rs 2/min and monthly subscription of Rs 30/ 30 days.

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

    ReplyDelete
  42. Great information

    videocon Entertainment now at your Finger tips! Simply click on "Vlive" in your SIM menu & choose from wide range of Information across the City, Entertainment & lots MORE on your mobile.

    ReplyDelete
  43. 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
  44. 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
  45. 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
  46. Really awesome blog. Your blog is really useful for me.
    Thanks for sharing this informative blog. Keep update your blog.
    Oracle Training In Chennai

    ReplyDelete
  47. Best Java Training Institute In ChennaiThis information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..

    ReplyDelete
  48. 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.
    cloud computing training in chennai | cloud computing courses in chennai

    ReplyDelete
  49. 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
  50. 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
  51. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

    ReplyDelete

  52. It was a great information and Its really worth enough reading it. The author did an mind blowing work by describing each and every concept in detail. Thanks for such an informative post. Please keep up your good work.
    Engineering Colleges In Chennai, Nautical Science Colleges In Chennai

    ReplyDelete
  53. Very informative ..i suggest this blog to my friends..Thank you for sharing
    MicroStrategy Online Training
    MicroStrategy Online Training Bangalore

    ReplyDelete
  54. 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.
    Android App Development Company

    ReplyDelete
  55. Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledge.
    Selenium Training in Chennai

    ReplyDelete
  56. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete

  57. 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
  58. 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.
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
  59. 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.
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text
    Mobile Marketing Services
    mobile marketing companies
    Sms API

    ReplyDelete
  60. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete