Compress Image Size (without reducing the quality) In Kotlin

edited May 2022 in Android

we will call like below :

compressImage(filePath, 0.5)

/ /file path means path of the file and 0.5 means target size of the image in MB


//in the below function we will image in file format
  fun compressImage(filePath: String, targetMB: Double = 1.0) : File {
        var file = File(filePath)
        var fullSizeBitmap: Bitmap = BitmapFactory.decodeFile(filePath)
        var exif = ExifInterface(filePath)
        val exifOrientation: Int = exif.getAttributeInt(
            ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL
        )
        val exifDegree: Int = exifOrientationToDegrees(exifOrientation)
        fullSizeBitmap = rotateImage(fullSizeBitmap, exifDegree.toFloat())

        try {

            val fileSizeInMB = getFileSizeInMB(filePath)
Log.d("TAG", "before compressImage: $fileSizeInMB")

            var quality = 100
            if(fileSizeInMB > targetMB){//1.0 means target MB
                quality = ((targetMB/fileSizeInMB)*100).toInt()
            }
            val fileOutputStream = FileOutputStream(filePath)
            fullSizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream)
            fileOutputStream.close()
Log.d("TAG", "after compressImage: ${getFileSizeInMB(filePath)}")
            file = File(filePath)
        }catch (e: Exception){
            e.printStackTrace()
        }
    return file
}
//here we get file size
 fun getFileSizeInMB(filePath: String): Double{
    val file = File(filePath)
    val length = file.length()
    val fileSizeInKB = (length/1024).toString().toDouble()
    return  (fileSizeInKB/1024).toString().toDouble()
}

//here we get rotation of the image 
 fun exifOrientationToDegrees(exifOrientation: Int): Int {
    return when(exifOrientation){
        ExifInterface.ORIENTATION_ROTATE_90 -> 90
        ExifInterface.ORIENTATION_ROTATE_180 -> 180
        ExifInterface.ORIENTATION_ROTATE_270 -> 270
        else -> 0
    }
}

//here we change the rotation of the captured image
 fun rotateImage(fullSizeBitmap: Bitmap, angle: Float): Bitmap {
    val matrix = Matrix()
    matrix.postRotate(angle)
    return Bitmap.createBitmap(fullSizeBitmap, 0, 0, fullSizeBitmap.width, fullSizeBitmap.height, matrix, true)


}


Sign In or Register to comment.