Skip to content

Instantly share code, notes, and snippets.

@tsuharesu
Created July 2, 2019 15:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsuharesu/833dc98230855f32e0f9719d60ca5e1e to your computer and use it in GitHub Desktop.
Save tsuharesu/833dc98230855f32e0f9719d60ca5e1e to your computer and use it in GitHub Desktop.
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