简体   繁体   中英

Android OutOfMemoryError when trying to rotate an image

I want to display an image on screen (I have an activity that displays an image):

Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
ExifInterface exif = new ExifInterface(imagePath);
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
matrix.preRotate(rotationInDegrees);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

The last line throws java.lang.OutOfMemoryError

I don't understand how to do this... I have to create the bitmap at first (BitmapFactory.decodeFile) but when I want to rotate it I have to provide the source bitmap already - how can I avoid it?

Thanks

You can try downsizing the image first before decoding it by adding inSampleSize in the bitmap options. as stated at the document: http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

Hope that helps.

If you aren't doing any crazy things elsewhere then your image is probably just too big.

You just need to increase your heap. Add this to your manifest file:

android:largeHeap="true"

You cannot rotate the bitmap in place, because the dimensions can be different. I don't know, why it's impossible to load already rotated bitmap.

You can rotate the bitmap in the place of use. When drawing the bitmap, use the rotation matrix to have it drawn with rotation.

Other thing is that you probably should review your app and try to minimize the memory usage. Maybe the bitmaps you use are too big and you should use Options with inSampleSize set to 2 or more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM