Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rotate image after saving with CameraX
/** Define callback that will be triggered after a photo has been taken and saved to disk */
private val imageSavedListener = object : ImageCapture.OnImageSavedListener {
override fun onError(error: ImageCapture.UseCaseError, message: String, exc: Throwable?) {
exc?.printStackTrace()
}
override fun onImageSaved(photoFile: File) {
lifecycle.coroutineScope.launch {
rotateImageCorrectly()
}
}
}
private suspend fun rotateImageCorrectly() = withContext(Dispatchers.IO) {
val sourceBitmap = MediaStore.Images.Media.getBitmap(contentResolver, photoFile.toUri())
val exif = ExifInterface(photoFile.inputStream())
val rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
val rotationInDegrees = when (rotation) {
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
}
val matrix = Matrix().apply {
if (rotation != 0) preRotate(rotationInDegrees.toFloat())
}
val rotatedBitmap =
Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.width, sourceBitmap.height, matrix, true)
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(photoFile))
sourceBitmap.recycle()
rotatedBitmap.recycle()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment