内存泄漏错误Android

时间:2012-11-06 09:28:45

标签: java android memory-leaks out-of-memory

InputSream backgroundBitmap;
//backgroundBitmap is initialized from asset image.png
immutableBitmap = BitmapFactory.decodeStream(backgroundBitmap);

收到此错误:

java.lang.OutOfMemoryError 在android.graphics.BitmapFactory.nativeDecodeAsset(本机方法)

帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

从资产

尝试此..文件
File f = new File("file:///android_assetassets/mydemo.png")

public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //The new size we want to scale to
            final int REQUIRED_WIDTH=WIDTH;
            final int REQUIRED_HIGHT=HIGHT;
            //Find the correct scale value. It should be the power of 2.
            int scale=1;
            while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
                scale*=2;

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        }
            catch (FileNotFoundException e) {}
        return null;
    }

当您传递宽度和高度时,此函数将缩放位图