Search code examples
androidandroid-gallery

Camera folder images appear rotated


I'm trying to process images in my app. The problem I'm currently facing is related to orientation of images. The thumbnail of the images selected from camera folder of Android appears 90 degrees rotated. I'm getting the thumbnail as following;

    Uri thumbUri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, uri.getLastPathSegment());
    if (thumbUri != null){
        try {
            List<String> parts = uri.getPathSegments();
            String lastPart = parts.get(parts.size() - 1);
            int index = lastPart.indexOf(":");
            if (index != -1)
            {
                lastPart = lastPart.substring(index+1);
            }
            long id = Long.parseLong(lastPart);

            // get a thumbnail for the image
            Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
                    context.getContentResolver(),
                    id,
                    MediaStore.Images.Thumbnails.MINI_KIND,
                    null
            );
            if (bitmap != null)
            {
                return bitmap;
            }
        }
        catch (Exception e)
        {
            Log.e(LOG_TAG, "Unable to generate thumbnail from thumbnail uri " + e.getMessage(), e);
        }

    }

Also tried to fix it by reading orientation from ExifInterface as;

ExifInterface ei = new ExifInterface(uri.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

But orientation returned is always 0 ORIENTATION_UNDEFINED. Unable to get what I'm doing wrong here.


Solution

  • Got the solution. I used getThumbnail(ContentResolver contentResolver, long id) method from BitmapUtil which reads the metadata of image from cursor and then process accordingly.

    Thanks to Jason Fry for this useful utility.