Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get orientation of image from MediaStore.Images.Media.DATA

i have MediaStore.Images.Media.DATA uri for an image how I can get MediaStore.Images.ImageColumns.ORIENTATION using that uri ? I am getting a NullPointerException.

Following is my code,

private  int getOrientation(Context context, Uri photoUri) {

Log.v("orientatioon", "not crashed01");
Cursor cursor = context.getContentResolver().query(photoUri,
        new String[] { MediaStore.Images.ImageColumns._ID,MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
Log.v("orientatioon", "not crashed02");


cursor.moveToFirst();
Log.v("orientatioon", "not crashed 03");
int i=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION));
Log.v("orientatioon", ""+i);
cursor.close();
return i;
}

I am getting a NullPointerException at cursor.moveToFirst() line of code.

like image 676
ultimate Avatar asked Nov 27 '22 05:11

ultimate


1 Answers

Actually both answers are right and they must be used simultaneously.

/**
 * @return 0, 90, 180 or 270. 0 could be returned if there is no data about rotation
 */
public static int getImageRotation(Context context, Uri imageUri) {
    try {
        ExifInterface exif = new ExifInterface(imageUri.getPath());
        int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

        if (rotation == ExifInterface.ORIENTATION_UNDEFINED)
            return getRotationFromMediaStore(context, imageUri);
        else return exifToDegrees(rotation);
    } catch (IOException e) {
        return 0;
    }
}

public static int getRotationFromMediaStore(Context context, Uri imageUri) {
    String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION};
    Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
    if (cursor == null) return 0;

    cursor.moveToFirst();

    int orientationColumnIndex = cursor.getColumnIndex(columns[1]);
    return cursor.getInt(orientationColumnIndex);
}

private static int exifToDegrees(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;
    } else {
        return 0;
    }
}
like image 51
eleven Avatar answered Dec 09 '22 16:12

eleven