본문 바로가기
프로그래밍/Android, iOS

[Android] Resize Bitmap

by YuminK 2022. 5. 11.

이미지가 들어왔을 때 원하는 width, height로 비율에 맞게 잘라준다.

https://stackoverflow.com/questions/4837715/how-to-resize-a-bitmap-in-android

 

스택오버플로우에서 scale처리하는 함수 토대로 만들었다. 

private fun getResizedBitmap(bm: Bitmap, destWidth: Int, destHeight: Int): Bitmap? {
    val width = bm.width
    val height = bm.height

    if(width >= height)
    {
        // 세로 기준으로 비율을 잡아 확대하고 이미지 좌우를 자른다.
        val heightRatio = (destHeight / height.toFloat())
        val matrix = Matrix()
        matrix.postScale(heightRatio, heightRatio)
        val resizedBitmap = Bitmap.createBitmap(
            bm, 0, 0, width, height, matrix, false
        )

        return Bitmap.createBitmap(
            resizedBitmap,
            (resizedBitmap.width - destWidth) / 2,
            0,
            destWidth,
            destHeight
        )
    }

    // 가로 기준으로 비율을 잡아 확대하고 이미지 위아래를 자른다.
    val widthRatio = (destWidth / width.toFloat())
    val matrix = Matrix()
    matrix.postScale(widthRatio, widthRatio)
    val resizedBitmap = Bitmap.createBitmap(
        bm, 0, 0, width, height, matrix, false
    )

    return Bitmap.createBitmap(
        resizedBitmap,
        0,
        (resizedBitmap.height - destHeight) / 2,
        destWidth,
        destHeight
    )
}

 

댓글