I would like to convert a landscape format into a portrait format. For this I use the following code. The problem is that the rotation in the end is not right, see second picture. What do I have to change?
private fun checkRotation(savedUri: Uri) {
val path = getRealPathFromURI(savedUri,this@NewStore)
val exif = ExifInterface(path!!)
val rotation =
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
val rotationInDegrees: Int = exifToDegrees(rotation)
val matrix = Matrix()
if (rotation != 0) {
matrix.postRotate(rotationInDegrees.toFloat())
}
val sourceBitmap = MediaStore.Images.Media.getBitmap(contentResolver, savedUri)
val rotatedBitmap =
Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.width, sourceBitmap.height, matrix, true)
val bitmap = rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(path!!))
sourceBitmap.recycle()
rotatedBitmap.recycle()
}
//exifOrientation has the value 6 here
private fun exifToDegrees(exifOrientation: Int): Int {
val rotationInDegrees = when (exifOrientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_270 -> 270
ExifInterface.ORIENTATION_TRANSVERSE -> -90
ExifInterface.ORIENTATION_TRANSPOSE -> -270
else -> 0
}
return rotationInDegrees
}
This is the original shot in landscape format
And that's after I did the rotation with ExifInterface
First, the rotation in the orientation tag is clockwise.
See: https://exiftool.org/TagNames/EXIF.html
While the rotation that
android.graphics.Matrix
performs is counterclockwise.So you should rotate -90 degrees for
ORIENTATION_ROTATE_90
for example.Second,
ORIENTATION_TRANSPOSE
andORIENTATION_TRANSVERSE
require rotation and flipping. You can combine rotation and scale in the same matrix for this.Third, you are not handling some of the possible orientations:
ORIENTATION_FLIP_HORIZONTAL
,ORIENTATION_FLIP_VERTICAL
. This can be done by scaling either X or Y by -1.