彻底解决Android因加载多个大图引起的OutOfMemoryError,内存溢出的问题
最近因为项目里需求是选择或者拍摄多张照片后,提供滑动预览和上传,很多照片是好几MB一张,因为目前的Android系统对运行的程序都有一定的内存限制,一般是16MB或24MB(视平台而定),不做处理直接加载的话必然会报OOM (Out Of Memmory)。网上有很多解决android加载bitmap内存溢出的方法,我总结了一个通用的方法,下面是我从的开发案例抽取出来的代码:
我在项目中建了个Util.java工具类,里面写了个方法,根据图片的路径返回一个字节流数组对象:
public static byte[] decodeBitmap(String path) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;// 设置成了true,不占用内存,只获取bitmap宽高
BitmapFactory.decodeFile(path, opts);
opts.inSampleSize = computeSampleSize(opts, -1, 1024 * 800);
opts.inJustDecodeBounds = false;// 这里一定要将其设置回false,因为之前我们将其设置成了true
opts.inPurgeable = true;
opts.inInputShareable = true;
opts.inDither = false;
opts.inPurgeable = true;
opts.inTempStorage = new byte[16 * 1024];
FileInputStream is = null;
Bitmap bmp = null;
ByteArrayOutputStream baos = null;
try {
is = new FileInputStream(path);
bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
double scale = getScaling(opts.outWidth * opts.outHeight,
1024 * 600);
Bitmap bmp2 = Bitmap.createScaledBitmap(bmp,
(int) (opts.outWidth * scale),
(int) (opts.outHeight * scale), true);
bmp.recycle();
baos = new ByteArrayOutputStream();
bmp2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
bmp2.recycle();
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
System.gc();
}
return baos.toByteArray();
} private static double getScaling(int src, int des) {
/**
* 48 目标尺寸÷原尺寸 sqrt开方,得出宽高百分比 49
*/
double scale = Math.sqrt((double) des / (double) src);
return scale;
} public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels); int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
} return roundedSize;
} private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight; int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) {
return lowerBound;
} if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
然后在我需要加载图片BitMap的地方来调用Util.decodeBitmap():
Bitmap bitmap = BitmapFactory.decodeByteArray(Util.decodeBitmap(imagePath), 0, Util.decodeBitmap(imagePath).length);
imageCache.put(imagePath, new SoftReference<Bitmap>(bitmap));
上面这两行是我的AsyncImageLoaderByPath类中的代码,用来加载SD卡里面的图片,该类完整代码是:
package com.pioneer.travel.util; import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap; import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView; public class AsyncImageLoaderByPath {
//SoftReference是软引用,是为了更好的为了系统回收变量
private HashMap<String, SoftReference<Bitmap>> imageCache;
private Context context; public AsyncImageLoaderByPath(Context context) {
this.imageCache = new HashMap<String, SoftReference<Bitmap>>();
this.context = context;
}
public Bitmap loadBitmapByPath(final String imagePath, final ImageView imageView, final ImageCallback imageCallback){
if (imageCache.containsKey(imagePath)) {
//从缓存中获取
SoftReference<Bitmap> softReference = imageCache.get(imagePath);
Bitmap bitmap = softReference.get();
if (bitmap != null) {
return bitmap;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Bitmap) message.obj, imageView, imagePath);
}
};
//建立新一个获取SD卡的图片
new Thread() {
@Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeByteArray(Util.decodeBitmap(imagePath), 0, Util.decodeBitmap(imagePath).length);
imageCache.put(imagePath, new SoftReference<Bitmap>(bitmap));
Message message = handler.obtainMessage(0, bitmap);
handler.sendMessage(message);
}
}.start();
return null;
}
//回调接口
public interface ImageCallback {
public void imageLoaded(Bitmap imageBitmap,ImageView imageView, String imagePath);
}
}
通过这个实例,我验证了一下,一次性获取20张5MB的照片,都可以加载的很流畅,完全没有再出现报OOM的错误了
以下是运行效果
SD卡中的图片:
进入应用,选择11张照片进行滑动预览:
希望以上所写对大家有帮助,谢谢!
彻底解决Android因加载多个大图引起的OutOfMemoryError,内存溢出的问题的更多相关文章
- 【转】解决Android因加载多个大图引起的OutOfMemoryError,内存溢出的问题
本文来自:http://blog.csdn.net/wulianghuan/article/details/11548373,感谢原作者的分享. 目标是读取SD卡中的图片并且展示出来 主要思路是通过一 ...
- Android高效加载大图、多图解决方案,有效避免程序OOM
高效加载大图片 我们在编写Android程序的时候经常要用到许多图片,不同图片总是会有不同的形状.不同的大小,但在大多数情况下,这些图片都会大于我们程序所需要的大小.比如说系统图片库里展示的图片大都是 ...
- Android图片加载库:最全面的Picasso讲解
前言 上文已经对当今 Android主流的图片加载库 进行了全面介绍 & 对比 如果你还没阅读,我建议你先移步这里阅读 今天我们来学习其中一个Android主流的图片加载库的使用 - Pica ...
- 演化理解 Android 异步加载图片
原文:http://www.cnblogs.com/ghj1976/archive/2011/05/06/2038738.html#3018499 在学习"Android异步加载图像小结&q ...
- Android 动态加载 (一) 态加载机制 案例一
在目前的软硬件环境下,Native App与Web App在用户体验上有着明显的优势,但在实际项目中有些会因为业务的频繁变更而频繁的升级客户端,造成较差的用户体验,而这也恰恰是Web App的优势.本 ...
- fackbook的Fresco (FaceBook推出的Android图片加载库-Fresco)
[Android开发经验]FaceBook推出的Android图片加载库-Fresco 欢迎关注ndroid-tech-frontier开源项目,定期翻译国外Android优质的技术.开源库.软件 ...
- Android Glide加载图片时转换为圆形、圆角、毛玻璃等图片效果
Android Glide加载图片时转换为圆形.圆角.毛玻璃等图片效果 附录1简单介绍了Android开源的图片加载框架.在实际的开发中,虽然Glide解决了快速加载图片的问题,但还有一个问题悬 ...
- Android动态加载so文件
在Android中调用动态库文件(*.so)都是通过jni的方式,而且往往在apk或jar包中调用so文件时,都要将对应so文件打包进apk或jar包,工程目录下图: 以上方式的存在的问题: 1.缺少 ...
- Android动态加载代码技术
Android动态加载代码技术 在开发Android App的过程当中,可能希望实现插件式软件架构,将一部分代码以另外一个APK的形式单独发布,而在主程序中加载并执行这个APK中的代码. 实现这个任务 ...
随机推荐
- SilverLight搭建WCF聊天室详细过程
收藏SL双工通信例子教程 SilverLight 4正式版发布给开发人员带来了更多功能,并且4已经支持NET.TCP协议,配合WCF开发高效率的交互应用程序已经不再是难事,本系列文章主要针对已经完成的 ...
- 内存(MRC)
一.计数器的基本操作1> retain : +1, 方法返回的是对象本身2> release :-13> retainCount : 获得计数器4> dealloc * 当一 ...
- J2SE知识点摘记(十七)
1. Applet Applet的生命周期分为四个阶段,各阶段分别由init,start,stop和destroy四种方法来具体体现. public void init() 此方法通知A ...
- redis存储session配制方法
redis存储session配制方法需要三个模块: 1.redis 2.express-session 3.connect-redis 项目中的配置方法代码片段如下: 首先连接redis,连接redi ...
- 达内TTS6.0课件oop_day03
- JAVA 内存的认识【转】
[转]:http://blog.sina.com.cn/s/blog_68158ebf0100wp83.html 一.Java内存的构成 先上一个官方java document里的图: 由上图 ...
- 【ActionBar的使用】
在AS工程中使用ActionBar 简单实用: 1.功能清单文件中指定主题标签属性Theme.Holo或其子类 <application android :theme="@androi ...
- C# 第三方控件 错误 LC-1
删掉项目下面的Properties\licenses.licx 文件
- BZOJ 1565: [NOI2009]植物大战僵尸( 最小割 )
先拓扑排序搞出合法的, 然后就是最大权闭合图模型了.... --------------------------------------------------------------------- ...
- pyhon MySQLdb查询出来的数据设置为字典类型
import MySQLdbimport MySQLdb.cursors cxn=MySQLdb.Connect(host='localhost',user='root',passwd='1234', ...