Created
July 2, 2019 15:01
-
-
Save tsuharesu/833dc98230855f32e0f9719d60ca5e1e to your computer and use it in GitHub Desktop.
Rotate image after saving with CameraX
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
/** 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