kotlin を使用し、新しい Android バージョンでの uri と exif の変更を考慮する:
var exif: ExifInterface? = null;
try {
when (Build.VERSION.SDK_INT) {
in Int.MIN_VALUE..24 -> exif = ExifInterface(imageUri.path)
else -> exif = ExifInterface(getContentResolver().openInputStream(data.extras.get("data")))
}
} catch (e: IOException) {
e.printStackTrace();
}
val orientation = exif?.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
bmp = rotateBitmap(bmp, orientation ?: ExifInterface.ORIENTATION_NORMAL)
そして、rotateBitmap 関数は次のとおりです。
un rotateBitmap(bitmap: Bitmap, orientation: Int): Bitmap {
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_NORMAL -> return bitmap
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
matrix.setRotate(180f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.setRotate(90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.setRotate(-90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
else -> return bitmap
}
try {
val bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
bitmap.recycle()
return bmRotated
} catch (e: OutOfMemoryError) {
e.printStackTrace()
return null
}
}