我得到了这个例外:
异常: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);
}
Run Code Online (Sandbox Code Playgroud)
如果异常告诉我我已经回收了resizedBitmap,那显然是错误的!我究竟做错了什么??
bsc*_*ltz 12
你实际上是bitmap.recycle();在这一行之后打电话:
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
Run Code Online (Sandbox Code Playgroud)
引用自Bitmap.createBitmap()方法的 Javadoc:
从源位图的子集中返回一个不可变的位图,由可选矩阵转换。新的位图可能是与源相同的对象,或者可能已经制作了一个副本。它以与原始位图相同的密度初始化。如果源位图是不可变的并且请求的子集与源位图本身相同,则返回源位图并且不创建新位图。
这意味着,在某些情况下,即要求来调整源位图到它的实际大小时,会出现没有区别源和调整大小后的位图。为了节省内存,该方法将只返回相同的位图实例。
要修复您的代码,您应该检查是否已创建新位图:
Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true);
if (resizedBitmap != sourceBitmap) {
sourceBitmap.recycle();
}
Run Code Online (Sandbox Code Playgroud)