回收的位图异常

时间:2012-01-30 22:16:12

标签: android

我遇到了这个例外:

异常:java.lang.IllegalStateException:无法复制回收的位图

我的代码是:

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int newWidth;
    int newHeight;
    if (width >= height) {
        newWidth = Math.min(width,1024);
        newHeight = (int) (((float)newWidth)*height/width);
    }
    else {
        newHeight = Math.min(height, 1024);
        newWidth = (int) (((float)newHeight)*width/height);
    }
    float scaleWidth = ((float)newWidth)/width;
    float scaleHeight = ((float)newHeight)/height;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    switch (orientation) {
    case 3:
        matrix.postRotate(180);
        break;
    case 6:
        matrix.postRotate(90);
        break;
    case 8:
        matrix.postRotate(270);
        break;
    }
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    bitmap.recycle();
    try {
        bitmap = resizedBitmap.copy(resizedBitmap.getConfig(), true);
    }
    catch (Exception e) {
        Log.v(TAG,"Exception: "+e);
    }

如果异常告诉我我已经回收了 resizedBitmap ,那显然是错误的!我做错了什么?

2 个答案:

答案 0 :(得分:12)

您实际上是在此行之后调用bitmap.recycle();

Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);

答案 1 :(得分:4)

引用来自Bitmap.createBitmap()方法的Javadoc:

  

从源位图的子集返回不可变位图,由可选矩阵转换。新位图可以是与源相同的对象,也可以是副本。它使用与原始位图相同的密度进行初始化。如果源位图是不可变的并且请求的子集与源位图本身相同,则返回源位图并且不会创建新的位图。

这意味着在某些情况下,即在要求将源位图的大小调整为实际大小时,调整大小位图之间没有区别。为了节省内存,该方法只返回位图的相同实例

要修复代码,您应该检查是否已创建新的位图:

Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true);
if (resizedBitmap != sourceBitmap) {
    sourceBitmap.recycle();
}