Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with large bitmap. Rotating and inserting to the gallery

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

like image 620
Arcantos Avatar asked Nov 06 '22 16:11

Arcantos


1 Answers

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().

like image 146
Gallal Avatar answered Nov 11 '22 04:11

Gallal