踩坑小计-Bitmap 使用中遇到的异常: trying to draw too large bitmap.

异常log:
Fatal Exception: java.lang.RuntimeException
Canvas: trying to draw too large(111590328bytes) bitmap.
这里有个疑惑这个size到底是怎么限制的呢,先了解bitmap占用内存的计算方式:
以Bitmap默认采用的色彩模式Bitmap.Config.ARGB_8888为例;在该模式中一共有四个通道,其中A表示Alpha,R表示Red,G表示Green,B表示Blue;并且这四个通道每个各占8位即一个字节,所以合起来共计4个字节。
即 bitmap占用内存 = width x height x 4
第二个问题,这个size的阈值是多少呢,查看文档找到了这个方法:
复制代码
 1  private static final int MAX_BITMAP_SIZE = 100 * 1024 * 1024; // 100 MB
 2 
 3     @Override
 4     protected void throwIfCannotDraw(Bitmap bitmap) {
 5         super.throwIfCannotDraw(bitmap);
 6         int bitmapSize = bitmap.getByteCount();
 7         if (bitmapSize > MAX_BITMAP_SIZE) {
 8             throw new RuntimeException(
 9                    "Canvas: trying to draw too large(" + bitmapSize +"bytes) bitmap.");
10         }
11     }
复制代码

这样就能在使用中限制bitmap的大小 防止崩溃了

复制代码
 1 //检查是否需要压缩
 2                         int width = r.getWidth();
 3                         int height = r.getHeight();
 4                         int inSampleSize = 1;
 5                         int max = 100 * 1024 * 1024;
 6                         while (width * height * 4 / inSampleSize > max){
 7                             inSampleSize *= 2;
 8                         }
 9                         if (inSampleSize > 1){
10                             Matrix m2 = new Matrix();
11                             m2.setScale(1 / (float)inSampleSize , 1 / (float)inSampleSize);
12                             r = Bitmap.createBitmap(r,0,0,width,height,m2,false);
13                         }
复制代码

 

posted @   Mr,Han  阅读(3820)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示