Android 位图大于 heapSize

标签 android bitmap out-of-memory

我收到错误:java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=12295KB, Allocated=3007KB, Bitmap Size=15621KB)

位图大小大于我的heapSize..那么我怎样才能使位图变小呢?这是它崩溃的代码:

private Bitmap getPicture(int position) {
    Bitmap bmpOriginal = BitmapFactory.decodeFile(mFileLocations.get(position));
    Bitmap bmResult = Bitmap.createBitmap(bmpOriginal.getWidth(), bmpOriginal.getHeight(), Bitmap.Config.RGB_565);
    Canvas tempCanvas = new Canvas(bmResult);
    tempCanvas.rotate(90, bmpOriginal.getWidth()/2, bmpOriginal.getHeight()/2);
    tempCanvas.drawBitmap(bmpOriginal, 0, 0, null);
    bmpOriginal.recycle();
}

它在行崩溃:

 Bitmap bmResult = Bitmap.createBitmap(bmpOriginal.getWidth(), bmpOriginal.getHeight(), Bitmap.Config.RGB_565);

和我的解码文件:

private Bitmap decodeFile(String f){
    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_SIZE=70;

        //Find the correct scale value. It should be the power of 2.
        int scale=1;
        while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
            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) {
        Log.d(LOG_TAG, "Failed to decode file");
    }
    return null;
}

最佳答案

缩小您的镜像以使其符合 VM 预算...

BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile( filename, options );
        options.inJustDecodeBounds = false;
        options.inSampleSize = 4; 

        bitmap = BitmapFactory.decodeFile( filename, options );
        if ( bitmap != null ) {
            bitmap = Bitmap.createScaledBitmap( bitmap, width, height, false );
        }

将样本大小更改为您想要的任何值,如 2、4、6、8 等。

有关详细信息,请参阅 this来自最近发布的 Android 开发者网站,它清楚地说明了您需要做什么才能达到 VM 预算。

关于Android 位图大于 heapSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10146393/

相关文章:

c# - 调用 WriteableBitmap.WritePixels 方法

javascript - 如何将类似react-native的js文件转换为纯javascript文件?

android - android中<include>和<ViewStub>的区别

android - Android Studio 中测试支持库的来源

c# - Image.RotateFlip 似乎没有旋转位图

java - Tomcat多次重新部署Web应用后如何解决Metaspace OOM?

android - 向 map 标记添加圆边

c++ - 图像到 ASCII 艺术转换

c# - StringWriter.ToString() 处的 OutOfMemoryException

c++ - C++ `new` 运算符可以在现实生活中抛出异常吗?