EasyImage
EasyImage copied to clipboard
Image get rotated by 90 degree
I am using Redmi Note 5 Pro device. Running Oreo. Whenever I am setting image to imageview it gets rotated automatically. Why is to so? How to resolve this?
@pravingaikwad123 Hi! It pretty known problem and unfortunately it's hardware related. Some producers mounts camera in different orientation. Imho it should be fixed automatically in library or at least library should provide helper than cam be called manually.
Example fix:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
EasyImage.handleActivityResult(requestCode, resultCode, data, this, object : DefaultCallback() {
override fun onImagePicked(imageFile: File?, source: EasyImage.ImageSource?, type: Int) {
if (source == EasyImage.ImageSource.CAMERA && imageFile != null) {
applyRotationIfNeeded(imageFile)
}
onPhotosReturned(imageFile)
}
override fun onImagePickerError(e: Exception?, source: EasyImage.ImageSource?, type: Int) {
//Some error handling
}
private fun applyRotationIfNeeded(imageFile: File) {
val exif = ExifInterface(imageFile.absolutePath)
val exifRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
val rotation = when(exifRotation) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_270 -> 270
else -> 0
}
if (rotation == 0) return
val bitmap = BitmapFactory.decodeFile(imageFile.absolutePath)
val matrix = Matrix().apply { postRotate(rotation.toFloat()) }
val rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
bitmap.recycle()
lateinit var out: FileOutputStream
try {
out = FileOutputStream(imageFile)
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
} catch (e: Exception) {
} finally {
rotatedBitmap.recycle()
out.close()
}
}
})
}