调用系统相册报out of memory 错误的解决办法

来源:互联网 发布:ac尼尔森数据 滑板 编辑:程序博客网 时间:2024/06/05 05:47

调用系统相册,用户选择图片后,将图片取出显示到imageview中。但是实际真机测试时发现有的图片正常返回,有的会报out of Memory 错误。错误详细是Biemap.Factory.decode错误,通过在网上搜索答案和自己实践,找到了解决办法。

之前调用系统相册的代码

 ContentResolver resolver = getContentResolver();Uri originalUri = data.getData();  //得到返回的Uri bitmap = MediaStore.Images.Media.getBitmap(resolver,originalUri);   //直接取出图片,会报错 this.imageView.setImageBitmap(smallBitmap);

改进后的代码


 ContentResolver resolver = getContentResolver();  Uri originalUri = data.getData();  String path=getFilePathFromContentUri(originalUri,resolver); //把uri 转换成path,后面才可以调用decodeFile

 BitmapFactory.Options options =new BitmapFactory.Options(); options.inJustDecodeBounds=true; bitmap=BitmapFactory.decodeFile(path, options); options.inJustDecodeBounds=false; int be=(int)(options.outHeight/(float)200); if(be<=0) be=1; options.inSampleSize = be; //设定缩放比例 bitmap=BitmapFactory.decodeFile(path, options); int w=bitmap.getWidth(); int h=bitmap.getHeight(); System.out.println(w+" "+h); bitmap= Bitmap.createScaledBitmap(bitmap, 350, 250, true); //使显示出来的bitmap都是固定大小 this.imageView.setImageBitmap(bitmap);


public int inSampleSize

Added in API level 1

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.

public boolean inJustDecodeBounds

Added in API level 1

If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

改进后,调用decode方法,就不再报out of memory错误


0 0
原创粉丝点击