오늘은 이미지가 자동 회전되는 현상을 방지하는 코드를 작성하였다.
원인을 알아본 결과 대부분 갤럭시로 촬영한 사진에서 이 현상이 발생하며, 정확한 원인은 잘 모르겠다.
인공지능은 정상적인 각도로 찍었을 때 만을 학습하였는데 이미지가 회전이 되면 인공지능이 인식을 못하기 때문에 회전을 방지해주어야 한다.
알아본 결과,
ExifiInterface의 메타데이터를 통해 회전을 해주면 된다고 한다.
ExifInterface.TAG_ORIENTATION 값이 회전된 각도이며 0이거나 null일 경우 회전이 되지 않은 것이며 값이 나올 경우 회전이 된 것이다.
코드는 다음과 같다.
try {
Bitmap bitmap;
try {
bitmap = DecodeBitmapFile(imagePath);
if (bitmap != null) {
ExifInterface ei = new ExifInterface(imagePath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Bitmap rotatedBitmap = null;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
rotatedBitmap = bitmap;
}
Bitmap bm =cropCenterBitmap(rotatedBitmap,512,512);
img2.setImageBitmap(bm);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
이전 글에서 작성한 절대 경로를 이용하는 코드
String imagePath = data.getDataString(); // "content://media/external/images/media/7215"
Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
imagePath = cursor.getString(index); // "/media/external/images/media/7215"
cursor.close();
에서 imagepath를 구한 후 경로를 bitmap으로 변환 후 출력 및 경로를 통한 ExifInterface의 값으로 이미지 회전도 방지한다.