안드로이드의 폰에서 찍은 사진은 내부적으로 카메라의 회전 정보가 담겨 있습니다. 폰으로 찍은 사진을 화면에 표시할때 이 화전 정보를 반영하여 촬영된 이미지를 표시해야 자연스럽습니다. 아래의 코드는 이미지 파일에 대한 회전 정보를 얻는 코드입니다.
val imageFilePath = "...... . jpg"
val ei = ExifInterface(imageFilePath)
val orientation: Int = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
val angle = when(orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90f
ExifInterface.ORIENTATION_ROTATE_180 -> 180f
ExifInterface.ORIENTATION_ROTATE_270 -> 270f
else -> 0f
}
위의 코드를 통해 이미지의 회전 각도르 얻어올 수 있고, 이를 토대로 이미지를 실제로 회전시키는 코드는 다음과 같습니다.
private fun resizeBitmap(src: Bitmap, size: Float, angle: Float): Bitmap {
val width = src.width
val height = src.height
var newWidth = 0f
var newHeight = 0f
if(width > height) {
newWidth = size
newHeight = height.toFloat() * (newWidth / width.toFloat())
} else {
newHeight = size
newWidth = width.toFloat() * (newHeight / height.toFloat())
}
val scaleWidth = newWidth.toFloat() / width
val scaleHeight = newHeight.toFloat() / height
val matrix = Matrix()
matrix.postRotate(angle);
matrix.postScale(scaleWidth, scaleHeight)
val resizedBitmap = Bitmap.createBitmap(src, 0, 0, width, height, matrix, true)
return resizedBitmap
}
위의 함수는 카메라로 찍은 이미지를 회전시켜 주는 것뿐만 아니라 이미지의 크기를 화면에 표시하기에 적당한 크기를 인자로 받아 줄여줍니다. 실제 사용하는 코드는 다음과 같습니다.
val imageFilePath = "...... . jpg"
val file = File(imageFilePath)
val angle = ...
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val source = ImageDecoder.createSource(contentResolver, Uri.fromFile(file))
ImageDecoder.decodeBitmap(source)?.let {
imageView.setImageBitmap(resizeBitmap(it, 900f, 0f))
}
} else {
MediaStore.Images.Media.getBitmap(contentResolver, Uri.fromFile(file))?.let {
imageView.setImageBitmap(resizeBitmap(it, 900f, 0f))
}
}