Android 中 加载Bitmap

[转]Android 中 加载Bitmap时,形成的Out of memory 问题


在Android中,对图片使用的内存是有限制的,加载的图片过大便出致使OOM问题。图像在加载过程当中,是把全部像素(即长*宽)加载到内存中,若是图片过大,便会致使java.lang.OutOfMemoryError问题,所以,在使用时要要加以注意。java



[java]  view plain copy print ?
  1. private static int MAX_IMAGE_DIMENSION = 720;  
  2.   
  3.    public Bitmap decodeFile(String filePath) throws IOException {  
  4.   
  5.        Uri photoUri = Uri.parse(filePath);  
  6.        InputStream is = this.getContentResolver().openInputStream(photoUri);  
  7.        BitmapFactory.Options dbo = new BitmapFactory.Options();  
  8.        dbo.inJustDecodeBounds = true;  
  9.        BitmapFactory.decodeStream(is, null, dbo);  
  10.        is.close();  
  11.   
  12.        int rotatedWidth, rotatedHeight;  
  13.     rotatedWidth = dbo.outWidth;  
  14.        rotatedHeight = dbo.outHeight;  
  15.         
  16.   
  17.        Bitmap mCurrentBitmap = null;  
  18.        is = this.getContentResolver().openInputStream(photoUri);  
  19.        if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {  
  20.            float widthRatio = ((float) rotatedWidth) / MAX_IMAGE_DIMENSION;  
  21.            float heightRatio = ((float) rotatedHeight) / MAX_IMAGE_DIMENSION;  
  22.            float maxRatio = Math.max(widthRatio, heightRatio);  
  23.            // Create the bitmap from file  
  24.            BitmapFactory.Options options = new BitmapFactory.Options();  
  25.            // 1.换算合适的图片缩放值,以减小对JVM太多的内存请求。  
  26.            options.inSampleSize = (int) maxRatio;  
  27.            // 2. inPurgeable 设定为 true,能够让java系统, 在内存不足时先行回收部分的内存  
  28.            options.inPurgeable = true;  
  29.            // 与inPurgeable 一块儿使用  
  30.            options.inInputShareable = true;  
  31.            // 3. 减小对Aphla 通道  
  32.            options.inPreferredConfig = Bitmap.Config.RGB_565;  
  33.            try {  
  34.                // 4. inNativeAlloc 属性设置为true,能够不把使用的内存算到VM里  
  35.                BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);  
  36.            } catch (IllegalArgumentException e) {  
  37.                e.printStackTrace();  
  38.            } catch (SecurityException e) {  
  39.                e.printStackTrace();  
  40.            } catch (IllegalAccessException e) {  
  41.                e.printStackTrace();  
  42.            } catch (NoSuchFieldException e) {  
  43.                e.printStackTrace();  
  44.            }  
  45.            // 5. 使用decodeStream 解码,则利用NDK层中,利用nativeDecodeAsset()  
  46.            // 进行解码,不用CreateBitmap  
  47.            mCurrentBitmap = BitmapFactory.decodeStream(is, null, options);  
  48.        } else {  
  49.            mCurrentBitmap = BitmapFactory.decodeStream(is);  
  50.        }  
  51.        return mCurrentBitmap;  
  52.    }