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;
}
出現(xiàn)異常的代碼是
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);
}
........
原圖和創(chuàng)建的圖片如果寬高一樣的情況下,可能直接會(huì)返回原圖,所以生成的圖片和原圖有可能是同一個(gè)對(duì)象。
在代碼中添加判斷,修改如下:
Bitmap newBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);
if (newBmp != bmp)
bmp.recycle();