I have an application that gets a fixed amount of images from the camera preview and converts them into a list of Bitmaps
. For that purpose I have the following code:
private Camera.PreviewCallback SetPreviewCallBack() {
return new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
List<Bitmap> imageList = new ArrayList<Bitmap>();
for (int i=0; i<30; i++) // Let's suppose this is the real loop.
// It's not, as the real loop takes each camera preview frame,
// instead of inserting the same one 30 times.
// But for this example, it's OK
{
imageList.add(GetBitmap(
data,
previewWidth, // Calculated
previewHeight, // Calculated
previewFormat, // Calculated
previewRotation)); // Calculated
}
}
private Bitmap GetBitmap(byte[] data, int width, int height, int previewFormat, int rotation) {
YuvImage yuv = new YuvImage(data, previewFormat, width, height, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuv.compressToJpeg(new Rect(0, 0, width, height), 50, out);
byte[] bytes = out.toByteArray();
final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Bitmap imageResult = RotateImage(bitmap, 4 - rotation);
bitmap.recycle();
return imageResult;
}
private Bitmap RotateImage(Bitmap rotateImage, int rotation) {
Matrix matrix = new Matrix();
switch (rotation) {
case 1:
matrix.postRotate(270);
break;
case 2:
matrix.postRotate(180);
break;
case 3:
matrix.postRotate(90);
break;
}
return Bitmap.createBitmap(rotateImage, 0, 0, rotateImage.getWidth(),
rotateImage.getHeight(), matrix, true);
}
What I do is:
- I store this image on a Singleton
class in order to access it from another Activity
contanied in my same application.
- I call again this piece of code (when some event happens) and repeat the image extraction/saving process.
03-05 09:35:13.339: E/AndroidRuntime(8762): FATAL EXCEPTION: Thread-818
03-05 09:35:13.339: E/AndroidRuntime(8762): java.lang.OutOfMemoryError
03-05 09:35:13.339: E/AndroidRuntime(8762): at android.graphics.Bitmap.nativeCreate(Native Method)
03-05 09:35:13.339: E/AndroidRuntime(8762): at android.graphics.Bitmap.createBitmap(Bitmap.java:726)
03-05 09:35:13.339: E/AndroidRuntime(8762): at android.graphics.Bitmap.createBitmap(Bitmap.java:703)
03-05 09:35:13.339: E/AndroidRuntime(8762): at android.graphics.Bitmap.createBitmap(Bitmap.java:636)
03-05 09:35:13.339: E/AndroidRuntime(8762): at com.facephi.sdk.ui.CameraPreview.RotateImage(CameraPreview.java:779)
03-05 09:35:13.339: E/AndroidRuntime(8762): at com.facephi.sdk.ui.CameraPreview.GetBitmap(CameraPreview.java:712)
I'm trying to use best practices to remove in the correct way unused Bitmaps
as posted here, but with no luck...
Any idea on why I'm having this OOM Error?