5

I need to take a picture with the camera and, if depending on the picture size, rotate it before saving it into the gallery.

I'm using

Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(imageCaptureIntent, IMAGE_CAPTURE);

To take the pic and save it to a temporary file.

Then

Bitmap bmp = BitmapFactory.decodeFile(imagePath);
String str = android.provider.MediaStore.Images.Media.insertImage(cr, bmp, name, description);

To save it.

This is the code i have tried to use to rotate the bitmap

Matrix matrix = new Matrix();
matrix.postRotate(180);
Bitmap x = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
android.provider.MediaStore.Images.Media.insertImage(cr, x, name, description);

The problem is I'm getting an OutOfMemoryException.

Is there a better way to handle the bitmaps to avoid breaking the memory?

~Thanks in advance, regards

Arcantos
  • 1,052
  • 1
  • 13
  • 28

2 Answers2

2

I don't think there is a better way to handle bitmaps. You could try to parse data directly from a file as Byte[] a portion at a time, and manipulating it in pieces; it's hard and you'll probably end up with very ugly code.

I also suggest the following:

  • Use android.provider.MediaStore.Images.Media.insertImage(cr, imagePath, name, description) instead of android.provider.MediaStore.Images.Media.insertImage(cr, bmp, name, description) this way there is no need to call Bitmap bmp = BitmapFactory.decodeFile(imagePath) and no bitmap will be loaded into memory at that point.

  • Throughout your code, make sure no bitmap is loaded unless needed. Set bitmaps that are no longer needed to null and call the garbage collector, or use bmp.recycle().

Gallal
  • 4,267
  • 6
  • 38
  • 61
  • bmp.recycle() wont help here cuz you can actually do it right AFTER you catch OOM. I mean after rotating bitmap and saving it. However the OOM most probably comes at rotating moment since it has to keep 2 same bitmaps in RAM there. – Stan Feb 16 '15 at 07:14
0

I had the same issue with rotating bitmap. The problem here:

    Bitmap bmp = BitmapFactory.decodeFile(imagePath); //this is the image you want to rotate
    // keeping in mind that you want to rotate the whole original image instead
    // of its downscaled copy you cant use BitmapFactory downscaling ratio
    Matrix matrix = new Matrix();
    matrix.postRotate(180);
    Bitmap x = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); 
    // the line above creates another bitmap so we have here 2 same sized bitmaps
    // even using the same var (bmp instead of x) wont change anything here
    // so you gonna get the OOM here

is that it creates 2 bitmaps so they want x2 more RAM.
Check my question and solution here. I bet for ImageMagick lib.

Community
  • 1
  • 1
Stan
  • 6,511
  • 8
  • 55
  • 87