我的应用程序中出现“无法压缩回收的位图错误”。它发生在我的代码中的 picture.compress(Bitmap.CompressFormat.PNG, 90, fos);
行上:
private void savePicture(byte[] data, String gameId, String folderName ) {
File pictureFile = getOutputMediaFile(gameId, folderName);
if (pictureFile == null){
Log.error("Error creating media file, check storage permissions.");
return;
}
Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length);
picture = getResizedBitmap(picture, bitmapWidth, bitmapHeight);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
picture.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
picture.recycle();
Log.info(">>> CameraActivity: PICTURE SAVED!");
} catch (FileNotFoundException e) {
Log.error(LibUtil.getStackTrace(e));
} catch (IOException e) {
Log.error(LibUtil.getStackTrace(e));
}
}
public Bitmap getResizedBitmap(Bitmap bmp, int newWidth, int newHeight) {
int width = bmp.getWidth();
int height = bmp.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bmp, 0, 0, width, height, matrix, false);
bmp.recycle();
return resizedBitmap;
}
但我觉得奇怪的是,当我注释掉 bmp.recycle();
行时,错误消失了。看起来(恕我直言)resizedBitmap
和 bmp
引用了相同的位图。但我不知道这样做是否正确,而且我的应用程序中没有内存泄漏或其他任何问题。
顺便说一句,此代码不会在任何 ImageView
上显示位图,而只是在幕后定期从相机拍摄照片并保存。
提前致谢。
最佳答案
createBitmap 的版本并不总是返回一个新的位图。在您的情况下,如果 resizedBitmap
等于 bmp
,则您正在回收两者(相同的引用)。在你的 getResizedBitmap
添加
if (resizedBitamp != bmp) {
bmp.recycle();
}
But I don't know whether it's the right thing to do and there's no memory leak or whatever in my app.
与内存泄漏无关。
关于android - 无法压缩回收的位图错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50987447/