Created
May 29, 2021 06:21
-
-
Save prongbang/2e6909e35b7c946ac4a6795dd12e102a to your computer and use it in GitHub Desktop.
RotationUtility.kt
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.BitmapFactory | |
import android.graphics.Matrix | |
import androidx.exifinterface.media.ExifInterface | |
import java.io.File | |
interface RotationUtility { | |
fun autoRotate(file: File): Bitmap | |
} | |
class ImageRotationUtility : RotationUtility { | |
override fun autoRotate(file: File): Bitmap { | |
val bitmap = BitmapFactory.decodeFile(file.absolutePath) | |
return try { | |
val exif = ExifInterface(file) | |
when (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, | |
ExifInterface.ORIENTATION_NORMAL)) { | |
ExifInterface.ORIENTATION_ROTATE_90 -> rotate(bitmap, 90) | |
ExifInterface.ORIENTATION_ROTATE_180 -> rotate(bitmap, 180) | |
ExifInterface.ORIENTATION_ROTATE_270 -> rotate(bitmap, 270) | |
else -> bitmap | |
} | |
} catch (ex: Exception) { | |
bitmap | |
} | |
} | |
private fun rotate(bitmap: Bitmap, orientation: Int): Bitmap { | |
val matrix = Matrix() | |
matrix.postRotate(orientation.toFloat()) | |
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