Image from gallery rotates automatically - Android

10.1k Views Asked by At

In my android application i am loading image from device gallery.In that, i am facing issue regarding image orientation. When i load large resolution images from gallery, they are automatically rotated then display in my view. I tried various solution regarding this problem but couldn't get proper solution. I referred getOrientation() , and this links. I have tried both solutions but couldn't got desired result.The ExifInterface return proper data but then also they are not helpful as images are rotated because of their large resolution not because of camera orientation. Please help me to solve this solution.

Thank you.

1

There are 1 best solutions below

0
On

This works well;

public class ExifUtils {

public static Bitmap getRotatedBitmap(Context context, Uri uri) {
    try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
        float width = (float) bitmap.getWidth();
        float height = (float) bitmap.getHeight();
        float max = Math.max(width / 1280.0f, height / 1280.0f);
        if (max > 1.0f) {
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (width / max), (int) (height / max), false);
        }
        Bitmap rotateBitmap = rotateBitmap(bitmap,
                new ExifInterface(context.getContentResolver().openInputStream(uri))
                        .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1));
        if (rotateBitmap != bitmap) {
            bitmap.recycle();
        }
        return rotateBitmap;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

private static Bitmap rotateBitmap(Bitmap bitmap, int i) {
    Matrix matrix = new Matrix();
    switch (i) {
        case 2:
            matrix.setScale(-1.0f, 1.0f);
            break;
        case 3:
            matrix.setRotate(180.0f);
            break;
        case 4:
            matrix.setRotate(180.0f);
            matrix.postScale(-1.0f, 1.0f);
            break;
        case 5:
            matrix.setRotate(90.0f);
            matrix.postScale(-1.0f, 1.0f);
            break;
        case 6:
            matrix.setRotate(90.0f);
            break;
        case 7:
            matrix.setRotate(-90.0f);
            matrix.postScale(-1.0f, 1.0f);
            break;
        case 8:
            matrix.setRotate(-90.0f);
            break;
        default:
            return bitmap;
    }
    try {
        Bitmap createBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        bitmap.recycle();
        return createBitmap;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        return null;
    }
  }
}