Loading Large Bitmaps Efficiently

This lesson teaches you to

  1. Read Bitmap Dimensions and Type
  2. Load a Scaled Down Version into Memory

Try it out

DOWNLOAD THE SAMPLE

DisplayingBitmaps.zip

Note: There are several libraries that follow best practices for loading images. You can use these libraries in your app to load images in the most optimized manner. We recommend the Glide library, which loads and displays images as quickly and smoothly as possible. Other popular image loading libraries include Picasso from Square and Fresco from Facebook. These libraries simplify most of the complex tasks associated with bitmaps and other types of images on Android.

Images come in all shapes and sizes. In many cases they are larger than required for a typical application user interface (UI). For example, the system Gallery application displays photos taken using your Android devices's camera which are typically much higher resolution than the screen density of your device.

Given that you are working with limited memory, ideally you only want to load a lower resolution version in memory. The lower resolution version should match the size of the UI component that displays it. An image with a higher resolution does not provide any visible benefit, but still takes up precious memory and incurs additional performance overhead due to additional on the fly scaling.

This lesson walks you through decoding large bitmaps without exceeding the per application memory limit by loading a smaller subsampled version in memory.

Read Bitmap Dimensions and Type


The BitmapFactory class provides several decoding methods (decodeByteArray()decodeFile()decodeResource(), etc.) for creating a Bitmap from various sources. Choose the most appropriate decode method based on your image data source. These methods attempt to allocate memory for the constructed bitmap and therefore can easily result in an OutOfMemory exception. Each type of decode method has additional signatures that let you specify decoding options via the BitmapFactory.Options class. Setting the inJustDecodeBounds property to true while decoding avoids memory allocation, returning null for the bitmap object but setting outWidthoutHeight and outMimeType. This technique allows you to read the dimensions and type of the image data prior to construction (and memory allocation) of the bitmap.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;

To avoid java.lang.OutOfMemory exceptions, check the dimensions of a bitmap before decoding it, unless you absolutely trust the source to provide you with predictably sized image data that comfortably fits within the available memory.

Load a Scaled Down Version into Memory


Now that the image dimensions are known, they can be used to decide if the full image should be loaded into memory or if a subsampled version should be loaded instead. Here are some factors to consider:

  • Estimated memory usage of loading the full image in memory.
  • Amount of memory you are willing to commit to loading this image given any other memory requirements of your application.
  • Dimensions of the target ImageView or UI component that the image is to be loaded into.
  • Screen size and density of the current device.

For example, it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x96 pixel thumbnail in an ImageView.

To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize to true in your BitmapFactory.Options object. For example, an image with resolution 2048x1536 that is decoded with an inSampleSize of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of ARGB_8888). Here’s a method to calculate a sample size value that is a power of two based on a target width and height:

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;     if (height > reqHeight || width > reqWidth) {         final int halfHeight = height / 2;
        final int halfWidth = width / 2;         // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }     return inSampleSize;
}

Note: A power of two value is calculated because the decoder uses a final value by rounding down to the nearest power of two, as per the inSampleSize documentation.

To use this method, first decode with inJustDecodeBounds set to true, pass the options through and then decode again using the new inSampleSizevalue and inJustDecodeBounds set to false:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {     // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);     // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);     // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

This method makes it easy to load a bitmap of arbitrarily large size into an ImageView that displays a 100x100 pixel thumbnail, as shown in the following example code:

mImageView.setImageBitmap(
    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

trying to draw too large(106,975,232 bytes) bitmap.的更多相关文章

  1. java.lang.RuntimeException: Canvas: trying to draw too large(203212800bytes) bitmap.

    https://www.cnblogs.com/spring87/p/7645625.html 今天我师父发现了一个问题:在更换登录页图片后,更新版本,部分手机打开会闪退.借了一个三星手机后,查看问题 ...

  2. java.lang.RuntimeException: Canvas: trying to draw too large(107331840bytes) bitmap.

    环境: Android 8.0.1 MIUI 真机测试闪退 gradle 4.1 compileSdkVersion 26 buildToolsVersion '26.0.2' minSdkVersi ...

  3. 异常:java.lang.RuntimeException: Canvas: trying to draw too large(161740800bytes) bitmap

    现象 今天做一个安卓项目的时候,我使用了10张图片,这10张图片都是放在了drawable目录下. 根据这个错误,我在网上寻找解决问题的方案,然后我放在了mipmap-xxhdpi下结果可以运行. 但 ...

  4. imageview无法显示图片:java.lang.RuntimeException: Canvas: trying to draw too large(281520000bytes) bitmap

    图片太大需要压缩. 压缩方法:http://jingyan.baidu.com/article/cdddd41c3ef41153ca00e162.html 如果特别大(几十M),可以先用在线的图片压缩 ...

  5. HTML5资料

    1 Canvas教程 <canvas>是一个新的用于通过脚本(通常是JavaScript)绘图的HTML元素.例如,他可以用于绘图.制作图片的组合或者简单的动画(当然并不那么简单).It ...

  6. MQTT_DEMO

    1 /* 2 Copyright (c) 2009-2012 Roger Light <roger@atchoo.org> 3 All rights reserved. 4 5 Redis ...

  7. Git Submodule使用完整教程

    Git Submodule功能刚刚开始学习可能觉得有点怪异,所以本教程把每一步的操作的命令和结果都用代码的形式展现给大家,以便更好的理解. 1.对于公共资源各种程序员的处理方式 每个公司的系统都会有一 ...

  8. Java程序员必备英文单词

    列表中共有769个单词,这些单词是从JDK.Spring.SpringBoot.Mybatis的源码中解析得到,按照在源码中出现的频次依次排列,页面中的单词是出现频次大于1000的.单词的音标.翻译结 ...

  9. Ehcache(2.9.x) - Configuration Guide, Configuring Storage Tiers

    About Storage Tiers Ehcache has three storage tiers, summarized here: Memory store – Heap memory tha ...

随机推荐

  1. HDU4768:Flyer [ 二分的奇妙应用 好题 ]

    传送门 Flyer Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total S ...

  2. Eclipse 语言文件下载地址

    http://www.eclipse.org/babel/downloads.php 更改配色: 安装新软件: http://eclipse-color-theme.github.com/update

  3. Spring 定时器 定时访问数据库并发送邮件

    我这里有两个案例的方法: 第一种:使用Spring quartz: 我这里使用的jar:spring-context-support.jar.quartz-1.6.5.jar ============ ...

  4. 2015多校联合训练赛 Training Contest 4 1008

    构造题: 比赛的时候只想到:前面一样的数,后面 是类似1,2,3,4,5,6....t这 既是:t+1,t+1...,1,2,3,...t t+1的数目 可能 很多, 题解时YY出一个N 然后对N   ...

  5. Codeforces 616 E Sum of Remainders

    Discription Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the resu ...

  6. 《Java虚拟机原理图解》 1.2、class文件中的常量池

    了解JVM虚拟机原理 是每一个Java程序员修炼的必经之路.但是由于JVM虚拟机中有很多的东西讲述的比较宽泛,在当前接触到的关于JVM虚拟机原理的教程或者博客中,绝大部分都是充斥的文字性的描述,很难给 ...

  7. JS --- 数组循环要用length

    socket.on("receive", function (data) { deviceone.print("返回的数据:"+data) // 发送异常 va ...

  8. 汉澳sinox通过ndis执行windows驱动程序

    汉澳sinox不仅能通过wine执行windows应用程序.还能通过ndis执行windows驱动程序 汉澳sinox使用 Windows NDIS 驱动程序 详细实现方法是用ndisgen把wind ...

  9. evaluate-reverse-polish-notation——栈

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are+,-,*, ...

  10. HTML初体验

    ios讨论群1群:135718460 HTML是英文Hyper Text Mark-up Language(超文本标记语言)的缩写,它规定了自己的语法规则,用来表示比"文本"更丰富 ...