踩坑小计-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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架