Search code examples
androidandroid-cameraandroid-gallery

Android Gallery Import


I am using gallery picker for picking an image from gallery. The photos taken by the camera in portrait mode is shown in the gallery as straight. But when I import the photos, i get the photo as rotated (landscape). Only gallery is showing this picture as straight. How to manage this problem? I want all photos as its actual orientation. Thanks in advance

private void addImageFromGallery() {

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),
            GALLERY_CODE);

}

Solution

  • Got the answer. The orientation is saved with the image in EXIF format. We have to read the Orientation tag of the data for each image..

    public static float rotationForImage(Context context, Uri uri) {
            if (uri.getScheme().equals("content")) {
            String[] projection = { Images.ImageColumns.ORIENTATION };
            Cursor c = context.getContentResolver().query(
                    uri, projection, null, null, null);
            if (c.moveToFirst()) {
                return c.getInt(0);
            }
        } else if (uri.getScheme().equals("file")) {
            try {
                ExifInterface exif = new ExifInterface(uri.getPath());
                int rotation = (int)exifOrientationToDegrees(
                        exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                ExifInterface.ORIENTATION_NORMAL));
                return rotation;
            } catch (IOException e) {
                Log.e(TAG, "Error checking exif", e);
            }
        }
            return 0f;
        }
    
        private static float exifOrientationToDegrees(int exifOrientation) {
        if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
            return 90;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
            return 180;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
            return 270;
        }
        return 0;
    }
    }
    

    The rotation value can be used to correct a photo’s orientation as follows:

    Matrix matrix = new Matrix();
    float rotation = PhotoTaker.rotationForImage(context, uri);
    if (rotation != 0f) {
          matrix.preRotate(rotation);
     }
    
    Bitmap resizedBitmap = Bitmap.createBitmap(
     sourceBitmap, 0, 0, width, height, matrix, true);