[问题集锦]Android Can't compress a recycled bitmap的解决方式

1、错误原因:

使用了已经被释放过内存的对象。

对于Bitmap:

Bitmap bitmap = 一个bitmap对象

使用过程中调用

bitmap.recycle()

之后再使用bitmap就会报错。

2. 图片裁剪时,按照下面的写法也易报错

public static Bitmap scaleBitmap(Bitmap bitmap,int newWidth){

int scaleWidth=newWidth;

float rate=(float)scaleWidth/bitmap.getWidth();

int scaleHeight= (int)(bitmap.getHeight()*rate);

Bitmap newBitmap=null;

if(bitmap!=null&&!bitmap.isRecycled()){

newBitmap= Bitmap.createScaledBitmap(bitmap, scaleWidth, scaleHeight, true);

if(newBitmap!=bitmap) {

//如果尺寸相同,不重复构建

bitmap.recycle();//销毁原有图片

}

}

return newBitmap;

}

原因是:当图片与裁剪后尺寸一致时,newBitmap不重复构建返回null 。bitmap被回收。所以推荐在执行完所有图片操作后,再将bitmap回收,尽量避免在图片操作过程中回收。

2、bitmap.recycle()解释:

recycle():

Free the native object associated with this bitmap, and clear the reference to the pixel data.