图片处理溢出

在用户发表评论的过程中,对于部分手机(万恶的红米NOTE2)如果从手机相册选择图片,程序OOM后crash。

修改前的代码是:

			        Uri uri = data.getData();   
			        ContentResolver cr = this.getContentResolver();   
			        try {
					Bitmap photo = BitmapFactory.decodeStream(cr.openInputStream(uri));
					if (photo != null) {
					    //为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存
				            if(pickbm != null){ 
				            	pickbm.recycle();}
				            //ImgaeTools.zoomBitmap是一个压缩图片的方法
				            pickbm = ImageTools.zoomBitmap(photo, photo.getWidth() / 10, photo.getHeight() / 10);
				            photo.recycle();
				        }
			        } catch (FileNotFoundException e) {  
			            e.printStackTrace();  
			        } catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}  
					picComment.setBackground(null);
					picComment.setImageBitmap(pickbm);
					savePhotoToSdcard(pickbm,GPUtils.getSharePicPath());
其中ImageTools.zoomBitmap()是一个压缩图片的方法
但是部分手机从相册选择后会OOM,看了 http://blog.csdn.net/huangbiao86/article/details/8072128后将代码修改入下:

			        Uri uri = data.getData();   
			        ContentResolver cr = this.getContentResolver();   
			        try {
			        	BitmapFactory.Options options = new BitmapFactory.Options();
			        	options.inSampleSize = 2;
						Bitmap photo = BitmapFactory.decodeStream(cr.openInputStream(uri), null, options);
						if (photo != null) {
							//为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存
				            if(pickbm != null){ 
				            	pickbm.recycle();
				            }  
				            pickbm = ImageTools.zoomBitmap(photo, photo.getWidth() / 10, photo.getHeight() / 10);
				            photo.recycle();
						}
			        } catch (FileNotFoundException e) {  
			            e.printStackTrace();  
			        } catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}  
					picComment.setBackground(null);
					picComment.setImageBitmap(pickbm);
					savePhotoToSdcard(pickbm,GPUtils.getSharePicPath());
其实主要是加了两句:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap photo = BitmapFactory.decodeStream(cr.openInputStream(uri), null, options);


示例一:通过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); 

你可能感兴趣的:(android,OOM)