회전된 사진을 원래 방향으로 가져오기

나고수·2022년 8월 28일
0

1일1공부

목록 보기
62/67

회전된 이미지를 원래 방향으로 가져오기
tip : glide 라이브러를 쓰면 알아서 방향 조정 해준다.
그런데 glide를 쓰면 bitmap이 원본 사이즈가 아닌 imageView 사이즈에 맞춰진 bitmap이 생성된다.
그런데 나는 imageView 사이즈에 맞춰진 작은 bitmap 이 아니라, 원래 사이즈 bitmap이 필요해서
glide를 사용하지 않고 직접 사진 회전을 구현했다.

//Exif : 사진찍은 위치,날짜, 사진 크기, 회전 정보 등 사진 정보가 들어있는 객체 를 알아낸다.
fun rotateOriginalBitmapByExif(bitmap: Bitmap?, context: Context, uri: Uri?): Bitmap? {
    var ei: ExifInterface? = null
    try {
        val `is` = context.contentResolver.openInputStream(uri!!)
        if (`is` != null) {
            ei = ExifInterface(`is`)
            `is`.close()
        }
    } catch (ignored: Exception) {
    }
    return if (ei != null) rotateOriginalBitmapByExif(bitmap, ei) else bitmap
}

//Exif에서 회전값을 알아낸 후 그 만큼 회전시킨다.
fun rotateOriginalBitmapByExif(bitmap: Bitmap?, exif: ExifInterface): Bitmap? {
    val degrees: Int = when (
        exif.getAttributeInt(
            ExifInterface.TAG_ORIENTATION,
            ExifInterface.ORIENTATION_NORMAL
        )
    ) {
        ExifInterface.ORIENTATION_ROTATE_90 -> 90
        ExifInterface.ORIENTATION_ROTATE_180 -> 180
        ExifInterface.ORIENTATION_ROTATE_270 -> 270
        else -> 0
    }

    val rotateMatrix = Matrix()
    rotateMatrix.postRotate(degrees.toFloat())

    return getRotatedOriginalBitmap(bitmap, degrees)
}

//이게 가로세로가 돌아가면서 , 사이즈가 안맞더라
//그래서 가로 /2 , 세로 /2 를 하니까 사이즈가 맞았다.
//createBitmap의 마지막 boolean은 true로 설정 시 
//이미지 pixel형태를 조정해 주어서 이미지가 선명하게 보이도록 도움을 준다.
//주의 : filter true 설정 시 , 너무 큰 이미지는 Out of memory 오류가 발생할 가능성이 크므로, 주의해서 사용하길 바람.
@Throws(java.lang.Exception::class)
fun getRotatedOriginalBitmap(bitmap: Bitmap?, degrees: Int): Bitmap? {
    if (bitmap == null) return null
    if (degrees == 0) return bitmap
    val m = Matrix()
    m.setRotate(degrees.toFloat(), bitmap.width.toFloat() / 2, bitmap.height.toFloat() / 2)
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, m, true)
}
profile
되고싶다

0개의 댓글