Android图片内存溢出的解决方案
- 作者: 据说开天辟地的是你爹
- 来源: 51数据库
- 2020-08-18
1.图片内存溢出
默认情况下,每个android程序的dailvik虚拟机的最大堆空间大小为16M
当加载的图片太多或图片过大时经常出现OOM问题
android 中用bitmap 时很容易内存溢出,报如下错误:Java.lang.OutOfMemoryError

2.解决办法
public Bitmap matrixBitmapSize(Bitmap bitmap, int screenWidth,
int screenHight) {
//获取当前bitmap的宽高
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scale = (float) screenWidth / w;
float scale2 = (float) screenHight / h;
// 取比例小的值 可以把图片完全缩放在屏幕内
scale = scale < scale2 ? scale : scale2;
// 都按照宽度scale 保证图片不变形.根据宽度来确定高度
matrix.postScale(scale, scale);
// w,h是原图的属性.
return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
}
public Bitmap optionsBitmapSize(String imagePath, int screenWidth,
int screenHight) {
// 设置解析图片的配置信息
BitmapFactory.Options options = new Options();
// 设置为true 不再解析图片 只是获取图片的头部信息及宽高
options.inJustDecodeBounds = true;
// 返回为null
BitmapFactory.decodeFile(imagePath, options);
// 获取图片的宽高
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
// 计算缩放比例
int scaleWidth = imageWidth / screenWidth;
int scaleHeight = imageHeight / screenHight;
// 定义默认缩放比例为1
int scale = 1;
// 按照缩放比例大的 去缩放
if (scaleWidth > scaleHeight & scaleHeight >= 1) {
scale = scaleWidth;
} else if (scaleHeight > scaleWidth & scaleWidth >= 1) {
scale = scaleHeight;
}
// 设置为true开始解析图片
options.inJustDecodeBounds = false;
// 设置图片的采样率
options.inSampleSize = scale;
// 得到按照scale缩放后的图片
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
return bitmap;
}
推荐阅读
热点文章
android中Bitmap用法(显示,保存,缩放,旋转)实例分析
12
android 仿微信聊天气泡效果实现思路
1
Android的尺度,drawable-xxxxxxx
2
Codeforces Round #656 (Div. 3) (C、D题)
1
Android之handler异步消息处理机制解析
6
GridView中图片显示出现上下间距过大,左右图片显示类似瀑布流的问题
0
AsyncTask的简单使用
5
两个简单Fragment之间的通信(三种方式)
18
uboot修改设置boot参数命令
41
android中实现从相册中一次性获取多张图片与拍照,并将选中的图片显示出来
2
