LoginSignup
8
4

More than 5 years have passed since last update.

Androidで、Exifを見て、画像を回転させる

Last updated at Posted at 2018-05-15

前提

  • Androidプログラミングの知識はないため、間違っている可能性があります。ご指摘をお願いいたします。

参考にしたサイト

https://qiita.com/neonankiti/items/e387a81a64d934ba8d9f
https://www.samieltamawy.com/how-to-fix-the-camera-intent-rotated-image-in-android/

build.gradleに、依存関係を追記します。

dependencies {
    implementation 'com.android.support:exifinterface:27.1.1'
}

Exifを見て、画像を回転させるメソッドを作ります。

ここでは、bitmapを引数で受けていますが、次のように、fileDescriptorから取り出すこともできます。
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);

@neonankiti様より、コメントを頂戴しました。ありがとうございます。

念のために書かせていただきますと、FileDescriptor自体はKitkat(OSバージョン4.4以上)からの導入ですので、それ未満のサポートを考えた場合には、私の記事にも書いておりますが、画像データはUriからストリームとして扱ってあげると良いかと思います。
https://qiita.com/neonankiti/items/e387a81a64d934ba8d9f

    /**
     * Rotate an image if required.
     * https://www.samieltamawy.com/how-to-fix-the-camera-intent-rotated-image-in-android/
     *
     * @param bitmap The image bitmap
     * @param context
     * @param uri    Image URI
     * @return The resulted Bitmap after manipulation
     */
    public static Bitmap rotateImageIfRequired(Bitmap bitmap, Context context, Uri uri) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor =
                context.getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

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

        parcelFileDescriptor.close();

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return rotateImage(bitmap, 90);
            case ExifInterface.ORIENTATION_ROTATE_180:
                return rotateImage(bitmap, 180);
            case ExifInterface.ORIENTATION_ROTATE_270:
                return rotateImage(bitmap, 270);
            default:
                return bitmap;
        }
    }

    /**
     * rotate image
     *
     * @param bitmap
     * @param degree
     * @return
     */
    private static Bitmap rotateImage(Bitmap bitmap, int degree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        Bitmap rotatedImg = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.recycle();
        return rotatedImg;
    }
8
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4