图片方向错误。如何修复

Orientation of picture is wrong. How to fix it

这是我的代码

 takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, "MyPicture");
                values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, 0);
            }
        });

@onActivityResult

 bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
 tempUri = getImageUri(getApplicationContext(), bitmap);
 s = getRealPathFromURI(tempUri);
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
 image.setImageBitmap(bitmap);

但是方向错了。 我认为使用 EXTRA_OUTPUT 时图像会旋转。但我不知道如何解决它。使用 ExifInterface。但是orientation一直是0。所以死锁了。

Attached file

Camera

Output

使用这 2 种方法获得正确旋转的位图,您只需调用 getPictureBitmap() 方法:

public Bitmap getPictureBitmap(String yourPathToPicture) throws IOException {
        Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);

        ExifInterface ei = new ExifInterface(yourPathToPicture);
        int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        Bitmap rotatedBitmap = null;
        switch(orientation) {

            case ExifInterface.ORIENTATION_ROTATE_90:
                rotatedBitmap = rotateImage(bitmap, 90);
                break;

            case ExifInterface.ORIENTATION_ROTATE_180:
                rotatedBitmap = rotateImage(bitmap, 180);
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                rotatedBitmap = rotateImage(bitmap, 270);
                break;

            case ExifInterface.ORIENTATION_NORMAL:
            default:
                rotatedBitmap = bitmap;
        }

        return rotatedBitmap;
    }

    public static Bitmap rotateImage(Bitmap source, float angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
                matrix, true);
    }