android 10 中使用图像 Uri 的毕加索图像旋转问题

picasso image rotation issue in android 10 using Uri of image

Picasso 在 android 10 中使用图像的 Uri 显示图像时出现图像旋转问题

Uri uri = "content://media/external/images/media/12155";
Picasso.get().load(uri).into(imageView);

我用的是最后一个版本2.8

这是原图

如果 android API 28 则未发现此问题,例如问题发生在大于或等于 android 29

这个class解决了问题

https://daniel.perez.sh/blog/2015/image-orientation-picasso/

package com.example.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import com.squareup.picasso.Transformation;

@TargetApi(Build.VERSION_CODES.KITKAT)
public class ExifTransformation implements Transformation {
    private static final String[] CONTENT_ORIENTATION = new String[] {
            MediaStore.Images.ImageColumns.ORIENTATION
    };

    final Context context;
    final Uri uri;

    public ExifTransformation(Context context, Uri uri) {
        this.context = context;
        this.uri = uri;
    }

    @Override
    public Bitmap transform(Bitmap source) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return source;

        int exifRotation = getExifOrientation(context, uri);
        if (exifRotation != 0) {
            Matrix matrix = new Matrix();
            matrix.preRotate(exifRotation);

            Bitmap rotated =
                    Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
            if (rotated != source) {
                source.recycle();
            }
            return rotated;
        }

        return source;
    }

    @Override
    public String key() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return "documentTransform()";
        return "documentExifTransform(" + uri.toString() + ")";
    }

    public static int getExifOrientation(Context context, Uri photoUri) {
        Cursor cursor = context.getContentResolver().query(photoUri, CONTENT_ORIENTATION, null, null, null);

        if (cursor.getCount() != 1) {
            return -1;
        }

        cursor.moveToFirst();
        return cursor.getInt(0);
    }
}

加载图片时,下面给出了想要的结果:

Picasso
    .with(this)
    .load(uri)
    .transform(new ExifTransformation(this, uri))
    .into(imageView);