在ImageView中旋转相机图像

时间:2020-08-25 15:32:27

标签: java android

我的imageview有问题。当我向其中添加方向(度)不为0°的照片时,它会自动将方向更改为0°。这意味着它将例如将90°的照片(垂直)变成0°的照片(水平)。可以在我的屏幕截图上看到示例。我该如何解决?

这是原始照片:1

这是旋转的照片:2

我本可以使用这段代码:

iv_add.setRotation(degree);

但这并不是我真正需要的,因为它可以旋转imageview而不是照片。

这是我的代码:

public String getRealPathFromURI(Uri contentUri) {

    String [] proj={MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery( contentUri,
            proj,
            null,
            null,
            null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();

    return cursor.getString(column_index);
}


public int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath) {
    int rotate = 0;
    try {
        context.getContentResolver().notifyChange(imageUri, null);
        File imageFile = new File(imagePath);
        ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
        }

        Log.i("RotateImage", "Exif orientation: " + orientation);
        Log.i("RotateImage", "Rotate value: " + rotate);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return rotate;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_COD) {
        Uri imageUri = data.getData();
        try {
            int rotateImage = getCameraPhotoOrientation(this, imageUri, getRealPathFromURI(imageUri));
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            Matrix matrix = new Matrix();
            matrix.preRotate(rotateImage);
            Bitmap rotBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            iv_add.setImageBitmap(rotBitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

有些照片实际上是完美的,但是其中一些消失了,甚至没有出现在我的imageview中

1 个答案:

答案 0 :(得分:0)

使用ExifInterface获取方向,并使用Matrix prerotate()相应地旋转图像。 ExifInterface Matrix