0

I am trying to make an extension function to use it in a different class. I am trying to create it but it does not work. Can anyone solve this problem.

Here is my extension:

fun resize.toBitmap(image: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap {
    var image = image
    return if (maxHeight > 0 && maxWidth > 0) {
        val width = image.width
        val height = image.height
        val ratioBitmap = width.toFloat() / height.toFloat()
        val ratioMax = maxWidth.toFloat() / maxHeight.toFloat()
        var finalWidth = maxWidth
        var finalHeight = maxHeight
        if (ratioMax > ratioBitmap) {
            finalWidth = (maxHeight.toFloat() * ratioBitmap).toInt()
        } else {
            finalHeight = (maxWidth.toFloat() / ratioBitmap).toInt()
        }
        image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true)
        image
    } else {
        image
    }

And this is how I try to reach it:

var bitmap = Bitmap.createBitmap(drawingCacheBitmap)
bitmap = resize(bitmap, 200, 100)

1 Answers1

0

Try this

fun Bitmap.resizeImage(image: Bitmap, maxWidth: Int, maxHeight: Int): Bitmap {
        val width = image.width
        val height = image.height
        val scaleWidth = maxWidth.toFloat() / width
        val scaleHeight = maxHeight.toFloat() / height
        
        val matrix = Matrix()
        
        matrix.postScale(scaleWidth, scaleHeight)

        // Create a New bitmap
        val resizedBitmap = Bitmap.createBitmap(
                image, 0, 0, width, height, matrix, false)
        resizedBitmap.recycle()
return resizedBitmap

}

And call this extension function like this,

bitmap = resizeImage(bitmap, 200, 100)
Mitesh Vanaliya
  • 2,491
  • 24
  • 39
  • Extension is working but now the size is extremely large and I can not set the size I use bitmap .resizeImage(bitmap, 200, 100) Old version (before extension) I could resize it as 200,100 now I can't see it even in screen – Muhittin Kaya Aug 21 '20 at 11:47
  • Again the same problem and what is the variable bm? I changed it to resizedBitmap and run. Again the same problem is carrying on. – Muhittin Kaya Aug 21 '20 at 12:46