Last active
July 12, 2018 12:05
-
-
Save JosiasSena/35dcf7f9e026e88535b482efd667bd42 to your computer and use it in GitHub Desktop.
Rotate an image/bitmap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.Bitmap | |
import android.graphics.Matrix | |
import android.support.media.ExifInterface | |
import java.io.File | |
class ImageUtils { | |
companion object { | |
/** | |
* Some devices take a photo side ways. Specially Samsung devices. This makes sure that the | |
* photo is rotated accordingly to make it straight again. | |
* | |
* @param bitmap the bitmap to be rotated | |
* @param file a file containing the bitmap | |
*/ | |
fun rotateBitmapIfNeeded(bitmap: Bitmap, file: File): Bitmap { | |
val matrix = Matrix() | |
val exifInterface = ExifInterface(file.path) | |
val orientationToRotateTo = exifInterface | |
.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) | |
val degreeToRotateTo = when (orientationToRotateTo) { | |
ExifInterface.ORIENTATION_ROTATE_90 -> 90f | |
ExifInterface.ORIENTATION_ROTATE_180 -> 180f | |
ExifInterface.ORIENTATION_ROTATE_270 -> 270f | |
else -> 0f | |
} | |
matrix.postRotate(degreeToRotateTo) | |
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment