前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java.lang.OutOfMemoryError处理

Java.lang.OutOfMemoryError处理

作者头像
听着music睡
发布2018-05-18 14:17:37
6930
发布2018-05-18 14:17:37
举报
文章被收录于专栏:Android干货

此错误对于新手做项目的时候经常会发生,而且不容易处理

默认情况下,每个android程序的dailvik虚拟机的最大堆空间大小为16M

当加载的图片太多或图片过大时经常出现OOM问题

而出现此类问题最常见的情况就是当我们使用BitMap类的时候

网上解决办法很多,这里贴出感觉最有用的一种解决办法

解决办法:

代码语言:javascript
复制
 1 public Bitmap matrixBitmapSize(Bitmap bitmap, int screenWidth,  
 2             int screenHight) {  
 3         //获取当前bitmap的宽高  
 4         int w = bitmap.getWidth();  
 5         int h = bitmap.getHeight();  
 6 
 7         Matrix matrix = new Matrix();  
 8         float scale = (float) screenWidth / w;  
 9         float scale2 = (float) screenHight / h;  
10 
11         // 取比例小的值 可以把图片完全缩放在屏幕内  
12         scale = scale < scale2 ? scale : scale2;  
13 
14         // 都按照宽度scale 保证图片不变形.根据宽度来确定高度  
15         matrix.postScale(scale, scale);  
16         // w,h是原图的属性.  
17         return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);  
18     }  
19 
20     public Bitmap optionsBitmapSize(String imagePath, int screenWidth,  
21             int screenHight) {  
22 
23         // 设置解析图片的配置信息  
24         BitmapFactory.Options options = new Options();  
25         // 设置为true 不再解析图片 只是获取图片的头部信息及宽高  
26         options.inJustDecodeBounds = true;  
27         // 返回为null  
28         BitmapFactory.decodeFile(imagePath, options);  
29         // 获取图片的宽高  
30         int imageWidth = options.outWidth;  
31         int imageHeight = options.outHeight;  
32         // 计算缩放比例  
33         int scaleWidth = imageWidth / screenWidth;  
34         int scaleHeight = imageHeight / screenHight;  
35         // 定义默认缩放比例为1  
36         int scale = 1;  
37         // 按照缩放比例大的 去缩放  
38         if (scaleWidth > scaleHeight & scaleHeight >= 1) {  
39             scale = scaleWidth;  
40         } else if (scaleHeight > scaleWidth & scaleWidth >= 1) {  
41             scale = scaleHeight;  
42         }  
43         // 设置为true开始解析图片  
44         options.inJustDecodeBounds = false;  
45         // 设置图片的采样率  
46         options.inSampleSize = scale;  
47         // 得到按照scale缩放后的图片  
48         Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);  
49         return bitmap;  
50     }

推荐一个程序员网站:

码农网

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-05-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档