Android大图片处理
来源:互联网 发布:win8装ubuntu双系统 编辑:程序博客网 时间:2024/05/17 06:13
移动设备对内存的要求还是很苛刻的,即便现在主流旗舰机动辄3G、4G的内存,但是对应于每个App分得的容量来说还是有限的,我们程序猿可以用各种手段来增大单个App的需求量,但是并不是完美的解决方案。最好是想办法来提高App的性能。图片来说更是OOM (OutOfMemoryError)的常见引发者,比如说系统图片库里展示的图片大都是用手机摄像头拍出来的,这些图片的分辨率会比我们手机屏幕的分辨率高得多。大家应该知道,我们编写的应用程序都是有一定内存限制的,程序占用了过高的内存就容易出现OOM(OutOfMemory)异常。接下来针对图片处理常见的手段一起看!
一、在内存引用上做些处理,常用的有软引用、强化引用、弱引用
在你应用程序的UI界面加载一张图片是一件很简单的事情,但是当你需要在界面上加载一大堆图片的时候,情况就变得复杂起来。在很多情况下,(比如使用ListView, GridView 或者 ViewPager 这样的组件),屏幕上显示的图片可以通过滑动屏幕等事件不断地增加,最终导致OOM。
为了保证内存的使用始终维持在一个合理的范围,通常会把被移除屏幕的图片进行回收处理。此时垃圾回收器也会认为你不再持有这些图片的引用,从而对这些图片进行GC操作。用这种思路来解决问题是非常好的,可是为了能让程序快速运行,在界面上迅速地加载图片,你又必须要考虑到某些图片被回收之后,用户又将它重新滑入屏幕这种情况。这时重新去加载一遍刚刚加载过的图片无疑是性能的瓶颈,你需要想办法去避免这个情况的发生。
这个时候,使用内存缓存技术可以很好的解决这个问题,它可以让组件快速地重新加载和处理图片。下面我们就来看一看如何使用内存缓存技术来对图片进行缓存,从而让你的应用程序在加载很多图片的时候可以提高响应速度和流畅性。
内存缓存技术对那些大量占用应用程序宝贵内存的图片提供了快速访问的方法。其中最核心的类是LruCache (此类在android-support-v4的包中提供) 。这个类非常适合用来缓存图片,它的主要算法原理是把最近使用的对象用强引用存储在 LinkedHashMap 中,并且把最近最少使用的对象在缓存值达到预设定值之前从内存中移除。
软引用(SoftReference)、虚引用(PhantomRefrence)、弱引用(WeakReference),这三个类是对heap中java对象的应用,通过这个三个类可以和gc做简单的交互,除了这三个以外还有一个是最常用的强引用。
1.1:强引用,例如下面代码:
Object o=new Object(); Object o1=o;
上面代码中第一句是在heap堆中创建新的Object对象通过o引用这个对象,第二句是通过o建立o1到new Object()这个heap堆中的对象的引用,这两个引用都是强引用。只要存在对heap中对象的引用,gc就不会收集该对象。如果通过如下代码:
o=null; o1=null
heap中对象有强可及对象、软可及对象、弱可及对象、虚可及对象和不可到达对象。应用的强弱顺序是强、软、弱、和虚。对于对象是属于哪种可及的对象,由他的最强的引用决定。如下:
String abc=new String("abc"); //1 SoftReference<String> abcSoftRef=new SoftReference<String>(abc); //2 WeakReference<String> abcWeakRef = new WeakReference<String>(abc); //3 abc=null; //4 abcSoftRef.clear();//5
上面的代码中:
第一行在heap对中创建内容为“abc”的对象,并建立abc到该对象的强引用,该对象是强可及的。第二行和第三行分别建立对heap中对象的软引用和弱引用,此时heap中的对象仍是强可及的。第四行之后heap中对象不再是强可及的,变成软可及的。同样第五行执行之后变成弱可及的。
1.2:软引用
软引用是主要用于内存敏感的高速缓存。在jvm报告内存不足之前会清除所有的软引用,这样以来gc就有可能收集软可及的对象,可能解决内存吃紧问题,避免内存溢出。什么时候会被收集取决于gc的算法和gc运行时可用内存的大小。当gc决定要收集软引用是执行以下过程,以上面的abcSoftRef为例:
- 首先将abcSoftRef的referent设置为null,不再引用heap中的new String(“abc”)对象。
- 将heap中的new String(“abc”)对象设置为可结束的(finalizable)。
- 当heap中的new String(“abc”)对象的finalize()方法被运行而且该对象占用的内存被释放, abcSoftRef被添加到它的ReferenceQueue中。
注:对ReferenceQueue软引用和弱引用可以有可无,但是虚引用必须有,参见:
Reference(T paramT, ReferenceQueue< ? super T>paramReferenceQueue)
被 Soft Reference 指到的对象,即使没有任何 Direct Reference,也不会被清除。一直要到 JVM 内存不足且 没有 Direct Reference 时才会清除,SoftReference 是用来设计 object-cache 之用的。如此一来 SoftReference 不但可以把对象 cache 起来,也不会造成内存不足的错误 (OutOfMemoryError)。我觉得 Soft Reference 也适合拿来实作 pooling 的技巧。
A obj = new A(); Refenrence sr = new SoftReference(obj); //引用时 if(sr!=null){ obj = sr.get(); }else{ obj = new A(); sr = new SoftReference(obj); }
1.3:弱引用
当gc碰到弱可及对象,并释放abcWeakRef的引用,收集该对象。但是gc可能需要对此运用才能找到该弱可及对象。通过如下代码可以了明了的看出它的作用:
String abc=new String("abc"); WeakReference<String> abcWeakRef = new WeakReference<String>(abc); abc=null; System.out.println("before gc: "+abcWeakRef.get()); System.gc(); System.out.println("after gc: "+abcWeakRef.get());
运行结果:
before gc: abc
after gc: null
gc收集弱可及对象的执行过程和软可及一样,只是gc不会根据内存情况来决定是不是收集该对象。如果你希望能随时取得某对象的信息,但又不想影响此对象的垃圾收集,那么你应该用 Weak Reference 来记住此对象,而不是用一般的 reference。
A obj = new A(); WeakReference wr = new WeakReference(obj); obj = null; //等待一段时间,obj对象就会被垃圾回收 ... if (wr.get()==null) { System.out.println("obj 已经被清除了 "); } else { System.out.println("obj 尚未被清除,其信息是 "+obj.toString()); } ... }
在此例中,透过 get() 可以取得此 Reference 的所指到的对象,如果返回值为 null 的话,代表此对象已经被清除。这类的技巧,在设计 Optimizer 或 Debugger 这类的程序时常会用到,因为这类程序需要取得某对象的信息,但是不可以 影响此对象的垃圾收集。
1.4:虚引用
就是没有的意思,建立虚引用之后通过get方法返回结果始终为null,通过源代码你会发现,虚引用通向会把引用的对象写进referent,只是get方法返回结果为null.先看一下和gc交互的过程在说一下他的作用.
1.4.1 不把referent设置为null, 直接把heap中的new String(“abc”)对象设置为可结束的(finalizable).
1.4.2 与软引用和弱引用不同, 先把PhantomRefrence对象添加到它的ReferenceQueue中.然后在释放虚可及的对象.
你会发现在收集heap中的new String(“abc”)对象之前,你就可以做一些其他的事情.通过以下代码可以了解他的作用.
import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.reflect.Field; public class Test { public static boolean isRun = true; public static void main(String[] args) throws Exception { String abc = new String("abc"); System.out.println(abc.getClass() + "@" + abc.hashCode()); final ReferenceQueue referenceQueue = new ReferenceQueue<String>(); new Thread() { public void run() { while (isRun) { Object o = referenceQueue.poll(); if (o != null) { try { Field rereferent = Reference.class .getDeclaredField("referent"); rereferent.setAccessible(true); Object result = rereferent.get(o); System.out.println("gc will collect:" + result.getClass() + "@" + result.hashCode()); } catch (Exception e) { e.printStackTrace(); } } } } }.start(); PhantomReference<String> abcWeakRef = new PhantomReference<String>(abc, referenceQueue); abc = null; Thread.currentThread().sleep(3000); System.gc(); Thread.currentThread().sleep(3000); isRun = false; }}
结果为
class java.lang.String@96354
二、在内存中加载图片时直接在内存中做处理,如:边界压缩
对于少量不太大的图片这种方式可行,但太多而又大的图片小马用个笨的方式就是,先在内存中压缩,再用软引用避免OOM。
首先解析一下基本的知识:
- 位图模式,bitmap颜色位数是1位
- 灰度模式,bitmap颜色位数是8位,和256色一样
- RGB模式,bitmap颜色位数是24位 在RGB模式下,一个像素对应的是红、绿、蓝三个字节
- CMYK模式,bitmap颜色位数是32位 在CMYK模式下,一个像素对应的是青、品、黄、黑四个字节
图像文件的字节数(Byte) = 图像分辨率*颜色深度/8(bit/8)
例如:一幅640*480图像分辨率、RGB色一般为24位真彩色,图像未经压缩的数据容量为:640X480X24/8=921600字节=900KB(1KB=l千字节=1024字节)。
注:一个图像文件占的磁盘空间大小还和磁盘的文件格式有关。如:NTFS最小单位为4KB 所以图像文件大小肯定是4KB的倍数。但是有图图片压缩算法的存在,图片文件在保存时,体积要比在内存的大小小得多,如640x480的图片文件大小一般只在200K~300K。这也是为什么,加载几MB的图片文件,会导致JVM内存溢出,导致OutofMemoryException的原因。
由上面的公式,我们可以得出,加载的图片所占的内存大小,取决于其分辨率和颜色数。
方式一代码如下:
@SuppressWarnings("unused") private Bitmap copressImage(String imgPath){ File picture = new File(imgPath); Options bitmapFactoryOptions = new BitmapFactory.Options(); //下面这个设置是将图片边界不可调节变为可调节 bitmapFactoryOptions.inJustDecodeBounds = true; bitmapFactoryOptions.inSampleSize = 2; int outWidth = bitmapFactoryOptions.outWidth; int outHeight = bitmapFactoryOptions.outHeight; bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), bitmapFactoryOptions); float imagew = 150; float imageh = 150; int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight / imageh); int xRatio = (int) Math .ceil(bitmapFactoryOptions.outWidth / imagew); if (yRatio > 1 || xRatio > 1) { if (yRatio > xRatio) { bitmapFactoryOptions.inSampleSize = yRatio; } else { bitmapFactoryOptions.inSampleSize = xRatio; } } bitmapFactoryOptions.inJustDecodeBounds = false; bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), bitmapFactoryOptions); if(bmap != null){ //ivwCouponImage.setImageBitmap(bmap); return bmap; } return null; }
方式二代码如下:
package com.lvguo.scanstreet.activity; import java.io.File; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; import com.lvguo.scanstreet.R; import com.lvguo.scanstreet.data.ApplicationData; /** * @Title: PhotoScanActivity.java * @Description: 照片预览控制类 * @author XiaoMa */ public class PhotoScanActivity extends Activity { private Gallery gallery ; private List<String> ImageList; private List<String> it ; private ImageAdapter adapter ; private String path ; private String shopType; private HashMap<String, SoftReference<Bitmap>> imageCache = null; private Bitmap bitmap = null; private SoftReference<Bitmap> srf = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.photoscan); Intent intent = this.getIntent(); if(intent != null){ if(intent.getBundleExtra("bundle") != null){ Bundle bundle = intent.getBundleExtra("bundle"); path = bundle.getString("path"); shopType = bundle.getString("shopType"); } } init(); } private void init(){ imageCache = new HashMap<String, SoftReference<Bitmap>>(); gallery = (Gallery)findViewById(R.id.gallery); ImageList = getSD(); if(ImageList.size() == 0){ Toast.makeText(getApplicationContext(), "无照片,请返回拍照后再使用预览", Toast.LENGTH_SHORT).show(); return ; } adapter = new ImageAdapter(this, ImageList); gallery.setAdapter(adapter); gallery.setOnItemLongClickListener(longlistener); } /** * Gallery长按事件操作实现 */ private OnItemLongClickListener longlistener = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { //此处添加长按事件删除照片实现 AlertDialog.Builder dialog = new AlertDialog.Builder(PhotoScanActivity.this); dialog.setIcon(R.drawable.warn); dialog.setTitle("删除提示"); dialog.setMessage("你确定要删除这张照片吗?"); dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { File file = new File(it.get(position)); boolean isSuccess; if(file.exists()){ isSuccess = file.delete(); if(isSuccess){ ImageList.remove(position); adapter.notifyDataSetChanged(); //gallery.setAdapter(adapter); if(ImageList.size() == 0){ Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoSizeZero), Toast.LENGTH_SHORT).show(); } Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoDelSuccess), Toast.LENGTH_SHORT).show(); } } } }); dialog.setNegativeButton("取消",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.create().show(); return false; } }; /** * 获取SD卡上的所有图片文件 * @return */ private List<String> getSD() { /* 设定目前所在路径 */ File fileK ; it = new ArrayList<String>(); if("newadd".equals(shopType)){ //如果是从查看本人新增列表项或商户列表项进来时 fileK = new File(ApplicationData.TEMP); }else{ //此时为纯粹新增 fileK = new File(path); } File[] files = fileK.listFiles(); if(files != null && files.length>0){ for(File f : files ){ if(getImageFile(f.getName())){ it.add(f.getPath()); Options bitmapFactoryOptions = new BitmapFactory.Options(); //下面这个设置是将图片边界不可调节变为可调节 bitmapFactoryOptions.inJustDecodeBounds = true; bitmapFactoryOptions.inSampleSize = 5; int outWidth = bitmapFactoryOptions.outWidth; int outHeight = bitmapFactoryOptions.outHeight; float imagew = 150; float imageh = 150; int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight / imageh); int xRatio = (int) Math .ceil(bitmapFactoryOptions.outWidth / imagew); if (yRatio > 1 || xRatio > 1) { if (yRatio > xRatio) { bitmapFactoryOptions.inSampleSize = yRatio; } else { bitmapFactoryOptions.inSampleSize = xRatio; } } bitmapFactoryOptions.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFile(f.getPath(), bitmapFactoryOptions); //bitmap = BitmapFactory.decodeFile(f.getPath()); srf = new SoftReference<Bitmap>(bitmap); imageCache.put(f.getName(), srf); } } } return it; } /** * 获取图片文件方法的具体实现 * @param fName * @return */ private boolean getImageFile(String fName) { boolean re; /* 取得扩展名 */ String end = fName .substring(fName.lastIndexOf(".") + 1, fName.length()) .toLowerCase(); /* 按扩展名的类型决定MimeType */ if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) { re = true; } else { re = false; } return re; } public class ImageAdapter extends BaseAdapter{ /* 声明变量 */ int mGalleryItemBackground; private Context mContext; private List<String> lis; /* ImageAdapter的构造符 */ public ImageAdapter(Context c, List<String> li) { mContext = c; lis = li; TypedArray a = obtainStyledAttributes(R.styleable.Gallery); mGalleryItemBackground = a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0); a.recycle(); } /* 几定要重写的方法getCount,传回图片数目 */ public int getCount() { return lis.size(); } /* 一定要重写的方法getItem,传回position */ public Object getItem(int position) { return lis.get(position); } /* 一定要重写的方法getItemId,传并position */ public long getItemId(int position) { return position; } /* 几定要重写的方法getView,传并几View对象 */ public View getView(int position, View convertView, ViewGroup parent) { System.out.println("lis:"+lis); File file = new File(it.get(position)); SoftReference<Bitmap> srf = imageCache.get(file.getName()); Bitmap bit = srf.get(); ImageView i = new ImageView(mContext); i.setImageBitmap(bit); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setLayoutParams( new Gallery.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT)); return i; } } }
上面两种方式第一种直接使用边界压缩,第二种在使用边界压缩的情况下间接的使用了软引用来避免OOM,但大家都知道,这些函数在完成decode后,最终都是通过java层的createBitmap来完成的,需要消耗更多内存,如果图片多且大,这种方式还是会引用OOM异常的,不着急,有的是办法解决,继续看,以下方式也大有妙用的:
InputStream is = this.getResources().openRawResource(R.drawable.pic1); BitmapFactory.Options options=new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = 10; //width,hight设为原来的十分一 Bitmap btp =BitmapFactory.decodeStream(is,null,options); if(!bmp.isRecycle() ){ bmp.recycle() //回收图片所占的内存 system.gc() //提醒系统及时回收 }
上面代码与下面代码大家可分开使用,也可有效缓解内存问题哦…吼吼…
/** 这个地方大家别搞混了,为了方便小马把两个贴一起了,使用的时候记得分开使用 * 以最省内存的方式读取本地资源的图片 */ public static Bitmap readBitMap(Context context, int resId){ BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; //获取资源图片 InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is,null,opt); }
再了解一下,android读取解析图片的方式,基本与Java的方式类型,通过文件输入流,然后进行解码,再转成图片格式;当然google的android也为我们封装好了若干方法,来方便快捷地完成这项工作,如ImageView的setImageBitmap,setImageResource,BitmapFactory的decodeResource等,但是尽量不要使用setImageBitmap或setImageResource或BitmapFactory.decodeResource来设置一张大图,因为这些函数在完成decode后,最终都是通过java层的createBitmap来完成的,需要消耗更多内存;
因此,改用先通过BitmapFactory.decodeStream方法,创建出一个bitmap,再将其设为ImageView的source,加载显示。decodeStream最大的秘密在于其直接调用JNI>>nativeDecodeAsset()来完成decode,无需再使用java层的createBitmap,从而节省了java层的空间。
在使用decodeStream读取图片时,再加上Config参数,就可以更有效地控制加载目标的内存大小,从而更有效阻止抛OutofMemoryException异常,下面用一段代码说明:
public static Bitmap readBitmapAutoSize(String filePath, int outWidth, int outHeight) { //outWidth和outHeight是目标图片的最大宽度和高度,用作限制 FileInputStream fs = null; BufferedInputStream bs = null; try { fs = new FileInputStream(filePath); bs = new BufferedInputStream(fs); BitmapFactory.Options options = setBitmapOption(filePath, outWidth, outHeight); return BitmapFactory.decodeStream(bs, null, options); } catch (Exception e) { e.printStackTrace(); } finally { try { bs.close(); fs.close(); } catch (Exception e) { e.printStackTrace(); } } return null; } private static BitmapFactory.Options setBitmapOption(String file, int width, int height) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; //设置只是解码图片的边距,此操作目的是度量图片的实际宽度和高度 BitmapFactory.decodeFile(file, opt); int outWidth = opt.outWidth; //获得图片的实际高和宽 int outHeight = opt.outHeight; opt.inDither = false; opt.inPreferredConfig = Bitmap.Config.RGB_565; //设置加载图片的颜色数为16bit,默认是RGB_8888,表示24bit颜色和透明通道,但一般用不上 opt.inSampleSize = 1; //设置缩放比,1表示原比例,2表示原来的四分之一.... //计算缩放比 if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) { int sampleSize = (outWidth / width + outHeight / height) / 2; opt.inSampleSize = sampleSize; } opt.inJustDecodeBounds = false;//最后把标志复原 return opt; }
另外,decodeStream直接拿的图片来读取字节码了, 不会根据机器的各种分辨率来自动适应, 使用了decodeStream之后,需要在hdpi和mdpi,ldpi中配置相应的图片资源, 否则在不同分辨率机器上都是同样大小(像素点数量),显示出来的大小就不对了。 可参考下面的代码:
BitmapFactory.Options opts = new BitmapFactory.Options(); //设置图片的DPI为当前手机的屏幕dpi opts.inTargetDensity = ctx.getResources().getDisplayMetrics().densityDpi; opts.inScaled = true;
三、动态回收内存,对象销毁
大家可以选择在合适的地方使用以下代码动态并自行显式调用GC来回收内存
if(bitmapObject.isRecycled()==false) //如果没有回收 bitmapObject.recycle();
四、优化Dalvik虚拟机的堆内存分配
这个就好玩了,优化Dalvik虚拟机的堆内存分配,听着很强大,来看下具体是怎么一回事。
对于Android平台来说,其托管层使用的Dalvik JavaVM从目前的表现来看还有很多地方可以优化处理,比如我们在开发一些大型游戏或耗资源的应用中可能考虑手动干涉GC处理,使用 dalvik.system.VMRuntime类提供的setTargetHeapUtilization方法可以增强程序堆内存的处理效率。当然具体原理我们可以参考开源工程,这里我们仅说下使用方法:
代码如下:
private final static float TARGET_HEAP_UTILIZATION = 0.75f; private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
在程序onCreate时就可以调用
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);
即可 。
五、自定义堆内存大小
我们可以通过下面的代码看出每个应用程序最高可用内存是多少。
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); Log.d("TAG", "Max memory is " + maxMemory + "KB");
因此在展示高分辨率图片的时候,最好先将图片进行压缩。压缩后的图片大小应该和用来展示它的控件大小相近,在一个很小的ImageView上显示一张超大的图片不会带来任何视觉上的好处,但却会占用我们相当多宝贵的内存,而且在性能上还可能会带来负面影响。下面我们就来看一看,如何对一张大图片进行适当的压缩,让它能够以最佳大小显示的同时,还能防止OOM的出现。
自定义我们的应用需要多大的内存,这个好暴力哇,强行设置最小内存大小,代码如下:
private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ; //设置最小heap内存为6MB大小 VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);
BitmapFactory这个类提供了多个解析方法(decodeByteArray, decodeFile, decodeResource等)用于创建Bitmap对象,我们应该根据图片的来源选择合适的方法。比如SD卡中的图片可以使用decodeFile方法,网络上的图片可以使用decodeStream方法,资源文件中的图片可以使用decodeResource方法。这些方法会尝试为已经构建的bitmap分配内存,这时就会很容易导致OOM出现。为此每一种解析方法都提供了一个可选的BitmapFactory.Options参数,将这个参数的inJustDecodeBounds属性设置为true就可以让解析方法禁止为bitmap分配内存,返回值也不再是一个Bitmap对象,而是null。虽然Bitmap是null了,但是BitmapFactory.Options的outWidth、outHeight和outMimeType属性都会被赋值。这个技巧让我们可以在加载图片之前就获取到图片的长宽值和MIME类型,从而根据情况对图片进行压缩。如下代码所示:
BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.id.myimage, options); int imageHeight = options.outHeight; int imageWidth = options.outWidth; String imageType = options.outMimeType;
为了避免OOM异常,最好在解析每张图片的时候都先检查一下图片的大小,除非你非常信任图片的来源,保证这些图片都不会超出你程序的可用内存。
现在图片的大小已经知道了,我们就可以决定是把整张图片加载到内存中还是加载一个压缩版的图片到内存中。以下几个因素是我们需要考虑的:
预估一下加载整张图片所需占用的内存。
为了加载这一张图片你所愿意提供多少内存。
用于展示这张图片的控件的实际大小。
当前设备的屏幕尺寸和分辨率。
比如,你的ImageView只有128*96像素的大小,只是为了显示一张缩略图,这时候把一张1024*768像素的图片完全加载到内存中显然是不值得的。
那我们怎样才能对图片进行压缩呢?
通过设置BitmapFactory.Options中inSampleSize的值就可以实现。比如我们有一张2048*1536像素的图片,将inSampleSize的值设置为4,就可以把这张图片压缩成512*384像素。原本加载这张图片需要占用13M的内存,压缩后就只需要占用0.75M了(假设图片是ARGB_8888类型,即每个像素点占用4个字节)。下面的方法可以根据传入的宽和高,计算出合适的inSampleSize值:
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // 源图片的高度和宽度 final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // 计算出实际宽高和目标宽高的比率 final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高 // 一定都会大于等于目标的宽和高。 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }
使用这个方法,首先你要将BitmapFactory.Options的inJustDecodeBounds属性设置为true,解析一次图片。然后将BitmapFactory.Options连同期望的宽度和高度一起传递到到calculateInSampleSize方法中,就可以得到合适的inSampleSize值了。之后再解析一次图片,使用新获取到的inSampleSize值,并把inJustDecodeBounds设置为false,就可以得到压缩后的图片了。
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // 调用上面定义的方法计算inSampleSize值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); }
下面的代码非常简单地将任意一张图片压缩成100*100的缩略图,并在ImageView上展示。
mImageView.setImageBitmap( decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
六、Bitmap 设置图片尺寸,避免内存溢出的优化方法
bitmap 设置图片尺寸,避免 内存溢出 OutOfMemoryError的优化方法
主要是加上这段:
BitmapFactory.Options options = new BitmapFactory.Options();options.inSampleSize = 2;
通过Uri取图片
private ImageView preview;BitmapFactory.Options options = new BitmapFactory.Options();options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之一Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, options);preview.setImageBitmap(bitmap);
以上代码可以优化内存溢出,但它只是改变图片大小,并不能彻底解决内存溢出。
通过路径去图片
private ImageView preview;private String fileName= "/sdcard/DCIM/Camera/2010-05-14 16.01.44.jpg";BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之一 Bitmap b = BitmapFactory.decodeFile(fileName, options); preview.setImageBitmap(b); filePath.setText(fileName);
七、使用图片缓存技术
在过去,我们经常会使用一种非常流行的内存缓存技术的实现,即软引用或弱引用 (SoftReference or WeakReference)。但是现在已经不再推荐使用这种方式了,因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠。另外,Android 3.0 (API Level 11)中,图片的数据会存储在本地的内存当中,因而无法用一种可预见的方式将其释放,这就有潜在的风险造成应用程序的内存溢出并崩溃。
为了能够选择一个合适的缓存大小给LruCache, 有以下多个因素应该放入考虑范围内,例如:
你的设备可以为每个应用程序分配多大的内存?
设备屏幕上一次最多能显示多少张图片?有多少图片需要进行预加载,因为有可能很快也会显示在屏幕上?
你的设备的屏幕大小和分辨率分别是多少?一个超高分辨率的设备(例如 Galaxy Nexus) 比起一个较低分辨率的设备(例如 Nexus S),在持有相同数量图片的时候,需要更大的缓存空间。
图片的尺寸和大小,还有每张图片会占据多少内存空间。
图片被访问的频率有多高?会不会有一些图片的访问频率比其它图片要高?如果有的话,你也许应该让一些图片常驻在内存当中,或者使用多个LruCache 对象来区分不同组的图片。
你能维持好数量和质量之间的平衡吗?有些时候,存储多个低像素的图片,而在后台去开线程加载高像素的图片会更加的有效。
并没有一个指定的缓存大小可以满足所有的应用程序,这是由你决定的。你应该去分析程序内存的使用情况,然后制定出一个合适的解决方案。一个太小的缓存空间,有可能造成图片频繁地被释放和重新加载,这并没有好处。而一个太大的缓存空间,则有可能还是会引起 java.lang.OutOfMemory 的异常。
下面是一个使用 LruCache 来缓存图片的例子:
private LruCache<String, Bitmap> mMemoryCache; @Override protected void onCreate(Bundle savedInstanceState) { // 获取到可用内存的最大值,使用内存超出这个值会引起OutOfMemory异常。 // LruCache通过构造函数传入缓存值,以KB为单位。 int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // 使用最大可用内存值的1/8作为缓存的大小。 int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { // 重写此方法来衡量每张图片的大小,默认返回图片数量。 return bitmap.getByteCount() / 1024; } }; } public void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { mMemoryCache.put(key, bitmap); } } public Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); }
在这个例子当中,使用了系统分配给应用程序的八分之一内存来作为缓存大小。在中高配置的手机当中,这大概会有4兆(32/8)的缓存空间。一个全屏幕的 GridView 使用4张 800x480分辨率的图片来填充,则大概会占用1.5兆的空间(800*480*4)。因此,这个缓存大小可以存储2.5页的图片。
当向 ImageView 中加载一张图片时,首先会在 LruCache 的缓存中进行检查。如果找到了相应的键值,则会立刻更新ImageView ,否则开启一个后台线程来加载这张图片。
public void loadBitmap(int resId, ImageView imageView) { final String imageKey = String.valueOf(resId); final Bitmap bitmap = getBitmapFromMemCache(imageKey); if (bitmap != null) { imageView.setImageBitmap(bitmap); } else { imageView.setImageResource(R.drawable.image_placeholder); BitmapWorkerTask task = new BitmapWorkerTask(imageView); task.execute(resId); } }
BitmapWorkerTask 还要把新加载的图片的键值对放到缓存中。
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> { // 在后台加载图片。 @Override protected Bitmap doInBackground(Integer... params) { final Bitmap bitmap = decodeSampledBitmapFromResource( getResources(), params[0], 100, 100); addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); return bitmap; } }
八、终极解决:高清加载巨图方案 拒绝压缩图片
BitmapRegionDecoder主要用于显示图片的某一块矩形区域,如果你需要显示某个图片的指定区域,那么这个类非常合适。
具体使用详看郭霖大神博客
文章来源
1、Android之解决太大太多图片造成的oom
2、有效解决Android加载大图片时内存溢出的问题
3、Android高效加载大图、多图解决方案,有效避免程序OOM
4、Android有效解决加载大图片时内存溢出的问题
- Android处理大图片
- Android大图片处理
- Android 处理大图片
- Android大图片处理
- Android大图片处理
- android 加载大图片处理
- Android的Bitmap处理大图片解决方法
- Android的Btimap处理大图片解决方法
- Android的Btimap处理大图片解决方案
- iOS处理大图片
- android_62_大图片处理
- Android 加载大图片
- android下载大图片
- android 加载大图片
- android加载大图片
- Android-加载大图片
- android加载大图片
- Android大图片裁剪
- 百度地图release.apk 地图不显示
- C++静态库与动态库
- js中数组的操作
- ES6篇let和conts命令
- 小萌谈Art(7)——让RobotArt打败小怪兽还我小萌猴
- Android大图片处理
- 硬盘各种分区格式最大单文件存储
- iOS 让你的app 支持与itunes之间传输文稿
- 【Android】android launchmode(四种启动模式)应用场景及实例
- 【yarn】全新JavaScript包管理工具【一】
- Hibernate查询的六种方式
- MacOS 删除.DS_Store并不再产生
- Android PackageManager 用法
- ES6变量的结构赋值