Skip to content

Instantly share code, notes, and snippets.

@JosiasSena
Last active July 12, 2018 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosiasSena/35dcf7f9e026e88535b482efd667bd42 to your computer and use it in GitHub Desktop.
Save JosiasSena/35dcf7f9e026e88535b482efd667bd42 to your computer and use it in GitHub Desktop.
Rotate an image/bitmap
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