Android EXIF data always 0, how to change it?

后端 未结 5 2189
[愿得一人]
[愿得一人] 2021-02-12 03:38

I have an app that captures photos using the native Camera and then uploads them to a server. My problem is that all the photos have an EXIF orientation value of 0,

5条回答
  •  独厮守ぢ
    2021-02-12 04:13

    As you can see, the The EXIF information is not reliable on Android (especially Samsung devices).

    However the phone SQL database holding the references to Media object is reliable. I would propose going this way.

    Getting the orientation from the Uri:

    private static int getOrientation(Context context, Uri photoUri) {
        Cursor cursor = context.getContentResolver().query(photoUri,
                new String[]{MediaStore.Images.ImageColumns.ORIENTATION}, null, null, null);
    
        if (cursor.getCount() != 1) {
            cursor.close();
            return -1;
        }
    
        cursor.moveToFirst();
        int orientation = cursor.getInt(0);
        cursor.close();
        cursor = null;
        return orientation;
    }
    

    Then initialize rotated Bitmap:

    public static Bitmap rotateBitmap(Context context, Uri photoUri, Bitmap bitmap) {
        int orientation = getOrientation(context, photoUri);
        if (orientation <= 0) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.postRotate(orientation);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        return bitmap;
    }
    

    If you want to change the orientation of the image, try the following snippet:

    public static boolean setOrientation(Context context, Uri fileUri, int orientation) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.ORIENTATION, orientation);
        int rowsUpdated = context.getContentResolver().update(fileUri, values, null, null);
        return rowsUpdated > 0;
    }
    

    If you set the orientation of the image, later it will be constantly set at the correct orientation. There is need to make use of ExifInterface later, because the image is already rotated in proper way.

    If this method is not satisfactory, then you could try this method

提交回复
热议问题