1.java.lang.IllegalStateException: Can't compress a recycled bitmap
public static String scaleImage(int maxWidth, File imageFile, String cacheDir) {
String path = imageFile.getPath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
DebugLog.e(TAG, "scaleImage::: maxWidth" + maxWidth + "; bmp.width=" + options.outWidth + ";" + imageFile.getPath());
Bitmap bmp = null;
if (options.outWidth <= maxWidth) {
return path;
} else if (options.outWidth > 4800) {
options.inJustDecodeBounds = false;
options.inSampleSize = 4;
bmp = BitmapFactory.decodeFile(path, options);
} else if (options.outWidth > 2400) {
options.inJustDecodeBounds = false;
options.inSampleSize = 2;
bmp = BitmapFactory.decodeFile(path, options);
} else {
options.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(path);
}
Matrix matrix = new Matrix();
float scale = maxWidth * 1.0f / options.outWidth;
matrix.setScale(scale, scale);
Bitmap newBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);
bmp.recycle();
bmp = null;
DebugLog.e(TAG, "scaleImage::: newBmp.height=" + newBmp.getHeight() + "; newBmp.width=" + newBmp.getWidth());
//压缩图片
String newFileName = "k_" + System.nanoTime() + "_book" + getImageType(imageFile.getPath());
File newImageFile = new File(cacheDir, newFileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(newImageFile);
newBmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
path = newImageFile.getPath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
closeStream(null, fos);
}
return path;
}
出现异常的代码是
Bitmap newBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);
bmp.recycle();
我们看一下Bitmap.createBitmap()的源码
public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height,
@Nullable Matrix m, boolean filter) {
checkXYSign(x, y);
checkWidthHeight(width, height);
if (x + width > source.getWidth()) {
throw new IllegalArgumentException("x + width must be <= bitmap.width()");
}
if (y + height > source.getHeight()) {
throw new IllegalArgumentException("y + height must be <= bitmap.height()");
}
// check if we can just return our argument unchanged
if (!source.isMutable() && x == 0 && y == 0 && width == source.getWidth() &&
height == source.getHeight() && (m == null || m.isIdentity())) {
return source;
}
boolean isHardware = source.getConfig() == Config.HARDWARE;
if (isHardware) {
source.noteHardwareBitmapSlowCall();
source = nativeCopyPreserveInternalConfig(source.mNativePtr);
}
........
原图和创建的图片如果宽高一样的情况下,可能直接会返回原图,所以生成的图片和原图有可能是同一个对象。
在代码中添加判断,修改如下:
Bitmap newBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);
if (newBmp != bmp)
bmp.recycle();