IT Convergence Engineering/AI 버섯 어플

[Android] imageView 사진 회전 현상 해결하기 & 사진의 절대경로명 찾기(JAVA)

Soo_buglosschestnut 2020. 8. 22. 19:52

imageView 사진 회전 현상 해결하기(JAVA)


  • 카메라로 찍은 사진 or 갤러리에서 불러온 사진이 imageView에서 회전되는 현상 발생!

 

 

 

 

 

 

 

  • 원래는 똑바른 사진인데 이렇게 왼쪽으로 회전 되어서 보임! (핸드폰 기종은 LG Q7)

 

 

 

 

 

 

 

 

 

→ 검색 해보니, 이미지 회전 현상이 빈번하게 발생하나 보다~ㅋㅋ

그러다 발견한 블로그!!

https://stickyny.tistory.com/95

 

안드로이드 이미지가 돌아갈 때, 회전될 때! Exif 메타정보 이용하기

샤오미 노트와 넥서스 기기에서는 재현되지 않는다. LG G4에서 재현된다. 앨범에 저장된 세로 이미지를 프로필 사진으로 등록하면 90도 회전되는 현상을 겪었다. 솔루션을 요약하자면, 사진의 메�

stickyny.tistory.com

  • Exif 메타데이터를 이용해 이미지를 회전 시켜주면 된다고 나와있다!!

더보기
  • Exif 메타데이터: 디지털 카메라 등에서 사용되는 이미지 파일 메타데이터 형식
  • 카메라 제조사(Maker)
  • 카메라 모델(Model)
  • 이미지 에디터(Software)
  • 사진을 보정한 날짜(Datetime)
  • Exif 버전(Exif Version)
  • 촬영한 날짜(Shoot Datetime)
  • 웹에 올려진 사진의 실제 크기(Image Size)
  • 노출 시간(Exposure Time:셔터 스피드)
  • 촬영 프로그램(Exposure Program)
  • 렌즈 초점 길이(Focal Length)
  • 조리개 개방 수치(F-Number)
  • 플래시 사용 여부 등 세부적인 부가정보를 기록할 수 있다.

출처: https://terms.naver.com/entry.nhn?docId=1254253&cid=40942&categoryId=32828

 

교환이미지 파일형식

디지털카메라의 이미지 파일 안에 저장되어 있는 화상 파일 형식이다. 약칭은 Exif 또는 EXIF이다. 일본전자공업진흥협회(JEIDA)에 의해 만들어졌다. 저장된 정보를 확인하려면 exif 규격을 지원하는

terms.naver.com

 

→ ExifiInterface class에서 ExifInterface.TAG_ORIENTATION 값이 회전된 각도이다. 

    이 값이 0 or null 이면 사진이 회전되지 않은것

    값이 있는 만큼 이미지를 회전 시켜주면 된다.

 

  • Exif Code
ExifInterface exif = null;
try {
    exif = new ExifInterface(path);
} catch (IOException e) {
    e.printStackTrace();
}  
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 
                                       ExifInterface.ORIENTATION_UNDEFINED);

→ 이렇게 Exif를 선언해주고 exif.getAttributeInt를 통해서 TAG_ORIENTATION값을 얻어 온다!

 

  • 회전할 이미지 bitmap Code
Bitmap bmRotated = rotateBitmap(#######, orientation);  

→ ######에는 원래 image(회전되서 나오는)의 bitmap변수를 적는다.

→ ###### image를 orientation만큼 rotate시킨 image를 bmRotated라 하겠다.

 

  • rotate 함수 Code
public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {

    Matrix matrix = new Matrix();
    switch (orientation) {
        case ExifInterface.ORIENTATION_NORMAL:
            return bitmap;
        case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
            matrix.setScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.setRotate(180);
            break;
        case ExifInterface.ORIENTATION_FLIP_VERTICAL:
            matrix.setRotate(180);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_TRANSPOSE:
            matrix.setRotate(90);
            matrix.postScale(-1, 1);
            break;
       case ExifInterface.ORIENTATION_ROTATE_90:
           matrix.setRotate(90);
           break;
       case ExifInterface.ORIENTATION_TRANSVERSE:
           matrix.setRotate(-90);
           matrix.postScale(-1, 1);
           break;
       case ExifInterface.ORIENTATION_ROTATE_270:
           matrix.setRotate(-90);
           break;
       default:
           return bitmap;
    }
    try {
        Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.recycle();
        return bmRotated;
    }
    catch (OutOfMemoryError e) {
        e.printStackTrace();
        return null;
    }
}

 

출처: https://stackoverflow.com/questions/20478765/how-to-get-the-correct-orientation-of-the-image-selected-from-the-default-image

 

How to get the Correct orientation of the image selected from the Default Image gallery

I have gone through some of the links to get the correct image orientation of the image selected from the default image gallery to be worked standard in all devices the exif tag always returns 0. ...

stackoverflow.com

https://stickyny.tistory.com/95

 

안드로이드 이미지가 돌아갈 때, 회전될 때! Exif 메타정보 이용하기

샤오미 노트와 넥서스 기기에서는 재현되지 않는다. LG G4에서 재현된다. 앨범에 저장된 세로 이미지를 프로필 사진으로 등록하면 90도 회전되는 현상을 겪었다. 솔루션을 요약하자면, 사진의 메�

stickyny.tistory.com


사진의 절대경로명 찾기(JAVA)

 

  • Camera로 찍은 Photo를 회전 시켜서 imageView에 띄우는거는 문제가 되지 않았다.

→ Photo를 File형식으로 만든다음 Photo.getAbsolutePath()를 이용해서 image를 rotate할 수 있다.

 

  • Camera 절대경로명/image rotate 관련 Code
// 사진의 회전 정보 얻어오는 부분
            ExifInterface exif = null;
            try {
                exif = new ExifInterface(mPhotoFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);


            // 찍은 사진 mPhotoFile을 bitmap으로 decodeFile
            Bitmap cameraphoto = BitmapFactory.decodeFile(mPhotoFile.getAbsolutePath());

            // 찍은 사진 rotate
            Bitmap cameraRotated = rotateBitmap(cameraphoto, orientation);
            // imageview 사진 뜨게함
            image.setImageBitmap(cameraRotated);
   

 

  • Album에서 사진을 골라오고 roate시키려고 하면 안된다!!

→ 진짜 경로명인 절대경로명을 써줘야한다고 발견...! 

 

  • Album에서 Pick한 image를 data라는 이름의 intent로 받는 Code

 

Uri filePath = data.getData();

→ data.getData()를 통해 Uri를 filePath라고 선언

 

  • Pick한 image의 절대경로명 Code
// 사진의 절대 경로명
Uri mPhotoUri = Uri.parse(getRealPathFromURI(filePath));

→ filePath라는 경로명에서 이제 진짜 경로명을 찾는 getRealPathFromURI 함수를 이용

 

  • getRealPathFromURI 함수 Code
// 사진의 절대경로명 찾게해줌 (album-rotate함수때 필요)
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx); cursor.close();
        }
        return result;
    }

→이렇게 해서 경로명 찾아준 후에 ExifInterface통해서 사진 rotate하면 됨!

 

  • Image rotate 관련 Code
ExifInterface exif = null;
try {

                int batchNum = 0;
                InputStream buf = getContentResolver().openInputStream(filePath);
                Bitmap albumphoto = BitmapFactory.decodeStream(buf);
                buf.close();

                // 사진의 회전 정보 얻어오는 부분
                exif = new ExifInterface(mPhotoUri.getPath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
                // 선택한 사진 rotate
                Bitmap albumRotated = rotateBitmap(albumphoto, orientation);
                // imageview 사진 뜨게함
                image.setImageBitmap(albumRotated);
                
                // ~~~~~~ 이 뒤에 다른 코드들 있음~
}

 

  • 실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

  • Code 적용 후에는 잘 rotate 된다!!

 

 

 

 

 

 

 

 

 

 

  • 출처

https://dd00oo.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-%EA%B0%A4%EB%9F%AC%EB%A6%AC%EC%9D%98-%EC%8B%A4%EC%A0%9C%EA%B2%BD%EB%A1%9C-%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0

 

[안드로이드] 갤러리의 실제경로 가져오기

managedQuery 메소드가 Deprecated 되었다. 이외에 startManagingCursor도 Deprecated 되었다. 그래서 새로운 방식으로 소스를 변경해야 했다. 예전의방식 public String getPath(Uri uri) { String[] projection..

dd00oo.tistory.com

 


ⓐ Album들어가는 Android code 정리 

github.com/buglossJisoo/AI_Mushroom_App

 

buglossJisoo/AI_Mushroom_App

AI Mushroom App final code(JAVA). Contribute to buglossJisoo/AI_Mushroom_App development by creating an account on GitHub.

github.com