Skip to content

Instantly share code, notes, and snippets.

@XinyueZ
Last active July 7, 2019 21:16
Show Gist options
  • Save XinyueZ/aba75863047a0b243197c4be9195bb89 to your computer and use it in GitHub Desktop.
Save XinyueZ/aba75863047a0b243197c4be9195bb89 to your computer and use it in GitHub Desktop.
Android: Read image file from disk, and upright.
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()
}
}
}
@gauravk95
Copy link

origin.recycle() and bitmap.recycle() not required here?

@XinyueZ
Copy link
Author

XinyueZ commented Jul 7, 2019

origin.recycle() and bitmap.recycle() not required here?

should be, should not be.
let the client programmer decide who uses these pieces codes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment