Android 循环位图异常

Android 循环位图异常,android,Android,我得到一个例外: 异常:java.lang.IllegalStateException:无法复制回收的位图 我的代码是: int width = bitmap.getWidth(); int height = bitmap.getHeight(); int newWidth; int newHeight; if (width >= height) { newWidth = Math.min(width,1024); n

我得到一个例外:

异常: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,那显然是错误的!我做错了什么???

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

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

引用方法的Javadoc:

从源位图的子集返回一个不可变位图,该位图由可选矩阵转换。新位图可能是与源相同的对象,或者可能已经制作了副本。它以与原始位图相同的密度初始化。如果源位图是不可变的,并且请求的子集与源位图本身相同,则返回源位图,并且不创建新位图

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

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

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

很可能当您分配到
resizedBitmap
时,它需要原始的,并且仍然绑定到原始的。您一定是在开玩笑吧!您的意思是createBitmap不会创建与“位图”不同的全新位图??WTF.it如果为堆栈跟踪附加了logcat,则会很有用…不要捕获异常…是的,createBitmap可以返回源位图:
//如果(!source.isMutable()&&x==0&&y==0&&width==source.getWidth()&&height==source.getHeight()&&height==source.getHeight()&&(m==null | | m.isIdentity()){返回源;}
你读过OP的最后一行了吗?他指出异常情况说他回收了
resizedBitmap
。他说他没有这样做,但他清楚地这样做。异常情况清楚地说明了问题。我认为问题是代码应该复制位图,然后根据表达式的顺序回收它。事实上我认为,运行时似乎不按顺序执行这些操作是造成混乱的原因。此外,抛出错误的副本是
try中的副本{
block,它正试图复制
resizedBitmap
并将其存储在
bitmap
中,而不是试图复制
bitmap
。好吧,我接受答案。这很愚蠢,但你能做什么?至少,它能工作。