Last active
July 7, 2019 21:16
-
-
Save XinyueZ/aba75863047a0b243197c4be9195bb89 to your computer and use it in GitHub Desktop.
Android: Read image file from disk, and upright.
This file contains 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
private fun Bitmap.rotate(degrees: Float): Bitmap { | |
val matrix = Matrix() | |
matrix.postRotate(degrees) | |
val scaledBitmap = Bitmap.createScaledBitmap(this, width, height, true) | |
return Bitmap.createBitmap( | |
scaledBitmap, | |
0, | |
0, | |
scaledBitmap.width, | |
scaledBitmap.height, | |
matrix, | |
true | |
) | |
} | |
private fun handleRotation(imgPath: String) { | |
BitmapFactory.decodeFile(imgPath)?.let { origin -> | |
try { | |
ExifInterface(imgPath).apply { | |
getAttributeInt( | |
ExifInterface.TAG_ORIENTATION, | |
ExifInterface.ORIENTATION_UNDEFINED | |
).let { orientation -> | |
when (orientation) { | |
ExifInterface.ORIENTATION_ROTATE_90 -> origin.rotate(270f) | |
ExifInterface.ORIENTATION_ROTATE_180 -> origin.rotate(180f) | |
ExifInterface.ORIENTATION_ROTATE_270 -> origin.rotate(90f) | |
ExifInterface.ORIENTATION_NORMAL -> origin | |
else -> origin | |
}.also { bitmap -> | |
//Update the input file with the new bytes. | |
try { | |
FileOutputStream(imgPath).use { fos -> | |
bitmap.compress( | |
Bitmap.CompressFormat.JPEG, | |
100, | |
fos | |
) | |
} | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} | |
} | |
} | |
} | |
} catch (e: IOException) { | |
e.printStackTrace() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
should be, should not be.
let the client programmer decide who uses these pieces codes.