Loading Large Bitmaps Efficiently in Android

原文地址:Loading Large Bitmaps Efficiently in Android
Loading large bitmaps into memory is always a pain. We all see OOM(Out Of Memory) errors in our crash reports because of large images. Android has a limited memory as we all know. We have to keep this in mind

There are lots of stackoverflow questions about that and you can just skip this blogpost and keep copy-pasting when you have OOM :) But for the rest, I want to give some information about loading large bitmap and how it actually works.

I wanted to give you logic behind decoding bitmaps. I suggest you to usePicasso** or Glide to load image. No need to reinvent the wheel.**

Load Bitmap Into Memory

It is easy. All you need is decode your image using BitmapFactory.

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.hqimage);
imageView.setImageBitmap(bitmap);

Seems everything is OK. But there is a problem which i am going to tell you. Let’s check out decoded bitmap size in our memory.

bitmap.getByteCount() method will return it’s size. Here is the total bytes of bitmap in the memory: 12262248 Bytes, which equals to 12,3 MB. Yes, you might be confused. You may think that Image’s actual size on disk is about 3.5 MB and getByteCount() is showing larger than disk size. Here is the reason:

The image is compressed when it is on disk (stored in a JPG, PNG, or similar format). Once you load the image into memory, it is no longer compressed and takes up as much memory as is necessary for all the pixels.

Steps

  • Get size of image without loading into memory
  • Calculate scale factor with image’s size.
  • Load bitmap into memory with calculated values.

BitmapFactory.Options

This class is a metadata provider for us. We can use this class to achieve first step.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.mipmap.hqimage, options);

We pass BitmapFactory.Options instance to *BitmapFactory.decodeSource() *method. You can see that we configured our “options” by setting inJustDecodeBounds true. What is the meaning of inJustDecodeBounds? It means that we don’t want to load bitmap into memory. We just want to get information(width, height, etc.) about image. So we can calculate scale factor with that information.

When we run this code and log options value:

options.outHeight : 1126
options.outWidth : 2000
options.bitmap : null

Here is the result. We have height, width. And I just wanted to see if bitmap is really null. Crosscheck: done.

Reducing Image Size (In Memory)

Now it is time to calculate inSampleSize. Wait. What is inSampleSize? inSampleSize is a scale factor that belongs to BitmapFactory.Options class.

If we have an image 1000x1000 and we set inSampleSize 2 before decoding. We will have 500x500 image after decoding operation. If we have 200x400 image and we set inSampleSize 5, we will have 40x80 image after decoding.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 3; 
BitmapFactory.decodeResource(getResources(), R.mipmap.hqimage, options);

Can we use it just like this? No. Because we don’t know what image size is. If it is small image and we make it more smaller, our user can see some pixels instead of image. Some images have to be scaled down 5 times. Some images have to be scaled down 2 times. We can not set scale factor as a constant. So we have to do a calculation according to image size.

Calculating inSampleSize is up to you. I mean, you can write your algorithm according to your needs. In android documentation, they calculate it power of two based. But you can also calculate your inSampleSize by incrementin it 1 by 1.

You can check the inSampleSize calculation code from android documentation.

options.inSampleSize = calculateInSampleSize(options, 500,500);
options.inJustDecodeBounds = false;
Bitmap smallBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.hqimage, options);

We switch inJustDecodeBounds to false and get bitmap with options instance.

Now, bitmap.getByteCount() method will return 3.1 MB. This is in memory size. As I said before, images are compressed when it is on disk. They are larger when we load them into memory.

We reduced from 12.3 MB to 3.1 MB. It is reduced %75 in MEMORY.

Reducing Image Size (In Disk)

We can also reduce image size in disk. We can compress our bitmap by using compress method of Bitmap.

Let’s check the file size without changing quality of bitmap image. 100 means same quality.

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();

When I calculate for original image, result is 1.6 MB on disk. Let’s change the quality and check the file size again.

<pre name="624a" id="624a" class="graf graf--pre graf-after--p" style="overflow: auto; font-family: Menlo, Monaco, "Courier New", Courier, monospace; font-size: 16px; margin: 43px 0px 0px; background: rgba(0, 0, 0, 0.05); padding: 20px; white-space: pre-wrap; color: rgba(0, 0, 0, 0.84); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);</pre>

I changed the quality to 50. And result is 24.4 KB.

Compress Format should be .JPEG if we want to change quality of bitmap. Quality can not be changed in PNG format.

We reduced file size from** 1.6 MB** to 24.4 KB.

Here is the result.

image.png

Don’t hesitate to ask/add something. Comments are welcome.

Happy coding.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 230,563评论 6 544
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,694评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,672评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,965评论 1 318
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,690评论 6 413
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 56,019评论 1 329
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 44,013评论 3 449
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 43,188评论 0 290
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,718评论 1 336
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,438评论 3 360
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,667评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,149评论 5 365
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,845评论 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,252评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,590评论 1 295
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,384评论 3 400
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,635评论 2 380

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,415评论 0 10
  • 西安纪游 3.回民风情和永兴坊美食街 空谷兰_6f4b 2018-04-24 12:30 · 字数 1230 · ...
    空谷兰_6f4b阅读 320评论 0 0
  • 每一天睡觉前脑子就像过电影一样,把所有应该做的,所有计划过一遍,然后就会产生特别大的惆怅感,近乎像焦虑症一样!事实...
    雨中诗文阅读 260评论 0 1
  • 1、定时器又称为延迟器,会在某个时间以后执行指定的代码 语法:Var timer=setTimeout(‘表达式’...
    清风沐沐阅读 382评论 0 0
  • 人呢,是一种难以琢磨的动物;人生呢,更是机缘巧合,因缘际遇,曲曲折折,兜兜转转,大概就是这样吧! 两年前,高考...
    DorisGe阅读 271评论 0 3