彻底解决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中的代码. 实现这个任务 ...
随机推荐
- AJAX获取JSON形式的数据
test.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...
- Probability theory
1.Probability mass functions (pmf) and Probability density functions (pdf) pmf 和 pdf 类似,但不同之处在于所适用的分 ...
- HTML5学习笔记之Input类型
Input类型——email email类型用于包含email地址的输入域,在输入地址时会自动验证email域的值 例:Email:<input type="email" n ...
- bash代码
bash代码: #!/bin/bash MySQLSTARTUP="/data/3306/mysql" DbProcessCount=`ps -ef|grep mysql|grep ...
- 2016 Multi-University Training Contest 4 总结
第四场多校队伍的发挥还是相当不错的. 我倒着看题,发觉最后一题树状数组可过,于是跟队友说,便开始写,十分钟AC. 欣君翻译01题给磊哥,发现是KMP裸题,但是发现模板太旧,改改后过了. 11题是一道毒 ...
- C++ 栈的实现
#ifndef _STACK_H #define _STACK_H #pragma once template< class T >class Stack{public: Stack( v ...
- javascript数组顺序-----1冒泡的另一种比较好理解的写法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- kafka学习(三)-kafka集群搭建
kafka集群搭建 下面简单的介绍一下kafka的集群搭建,单个kafka的安装更简单,下面以集群搭建为例子. 我们设置并部署有三个节点的 kafka 集合体,必须在每个节点上遵循下面的步骤来启动 k ...
- SPOJ QTREE4 lct
题目链接 这个题已经处于花式tle了,改版后的spoj更慢了.. tle的话就多交几把... #include <iostream> #include <fstream> #i ...
- ExecuteScalar
ExecuteScalar运行查询,并返回查询所返回的结果集中第一行的第一列或空引用(假设结果集为空).忽略其它列或行. 使用 ExecuteScalar 方法从数据库中检索单个值. 由于不用创建行集 ...