我使用camera.addCallbackBuffer(data);
重用缓冲区以避免内存不足。我在 previewCallback 中的代码就像
checkFace(data, camera);
camera.addCallbackBuffer(data);
在方法 checkFace 中,只需将数据转换为位图,然后使用 FaceDetector 来检查人脸。而且我在转换数据后尝试使用camera.addCallbackBuffer(data);
,但是Android Studio分析器中显示的本机内存就像
在我的应用程序运行大约 10 分钟后,“本机”从 10MB 增加到 250MB。
当我的应用程序运行大约 4 小时时,它会崩溃并 Logcat 打印:
E/IMemory (17967): 无法映射 BpMemoryHeap (binder=0x11515160), size=462848, fd=70 (Out of memory)
我想可能是因为越来越多的“原生”记忆
代码:
camera1.setPreviewCallbackWithBuffer(previewCallback1);
camera1.addCallbackBuffer(buffer1);
camera1.startPreview();
...
private Camera.PreviewCallback previewCallback1 = (data, camera) -> {
checkFace(data, camera);
camera.addCallbackBuffer(data);
};
//convert data to bitmap then check face from the bitmap
private void checkFace(byte[] data, Camera camera){
...
...run on new Thread...
Bitmap bitmap = BitmapUtil.ByteToBitmap(data, camera.getParameters().getPreviewSize());
...
FaceDetector detector = new FaceDetector(bitmap.getWidth(), bitmap.getHeight(), numberOfFace);
...then get the result of face detection
}
//convert frame data to bitmap
public static Bitmap ByteToBitmap(byte[] data, Camera.Size previewSize) {
ByteArrayOutputStream baos = null;
Bitmap bitmapOut = null;
try {
int w = previewSize.width;
int h = previewSize.height;
YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, w, h, null);
baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, w, h), 60, baos);
byte[] jdata = baos.toByteArray();
bitmapOut = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
if (null == bitmapOut) {
return bitmapOut;
}
jdata = null;
yuvimage = null;
Matrix matrix = new Matrix();
matrix.postRotate(90);
bitmapOut = Bitmap.createBitmap(bitmapOut, 0, 0, w, h, matrix, false);
} catch (Exception e) {
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (Exception e) {
}
}
return bitmapOut;
}
那么,我该怎么做才能解决它???