android kotlin - Bitmap scale down with aspect ratio

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.widget.*
import java.io.IOException

class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)
        val imageView2 = findViewById<ImageView>(R.id.imageView2)
        val textView = findViewById<TextView>(R.id.textView)
        val textView2 = findViewById<TextView>(R.id.textView2)
        val button = findViewById<Button>(R.id.button)


        // get the bitmap from assets folder
        val bitmap = assetsToBitmap("flower2.jpg")


        // If bitmap is not null
        bitmap?.let {
            imageView.setImageBitmap(bitmap)

            // Display the original bitmap's width and height
            textView.text = "${bitmap.width} * ${bitmap.height}"
        }


        // Click listener for button widget
        button.setOnClickListener{
            // disable the button itself
            it.isEnabled = false

            if(bitmap!=null){
                // Resize the bitmap by keeping aspect ratio
                // Bitmap scaled to given maximum height and width value
                val resizedBitmap = bitmap.scale(500)

                // Display the resized bitmap into image view
                imageView2.setImageBitmap(resizedBitmap)

                // Display the resized bitmap width and height
                textView2.text = "${resizedBitmap.width}" +
                        " * ${resizedBitmap.height}"

                // Show a toast message
                toast("Bitmap resized.")
            }else{
                toast("bitmap not found.")
            }
        }
    }



    // Method to get a bitmap from assets
    private fun assetsToBitmap(fileName:String):Bitmap?{
        return try{
            val stream = assets.open(fileName)
            BitmapFactory.decodeStream(stream)
        }catch (e:IOException){
            e.printStackTrace()
            null
        }
    }
}



// Extension method to resize bitmap to maximum width and height
fun Bitmap.scale(maxWidthAndHeight:Int):Bitmap{
    var newWidth = 0
    var newHeight = 0

    if (this.width >= this.height){
        val ratio:Float = this.width.toFloat() / this.height.toFloat()

        newWidth = maxWidthAndHeight
        // Calculate the new height for the scaled bitmap
        newHeight = Math.round(maxWidthAndHeight / ratio)
    }else{
        val ratio:Float = this.height.toFloat() / this.width.toFloat()

        // Calculate the new width for the scaled bitmap
        newWidth = Math.round(maxWidthAndHeight / ratio)
        newHeight = maxWidthAndHeight
    }

    return Bitmap.createScaledBitmap(
        this,
        newWidth,
        newHeight,
        false
    )
}



// Extension function to show toast message
fun Context.toast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="225dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Original Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Scale Down Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textView" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="225dp"
        android:layout_marginTop="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Scaled Bitmap"
        app:layout_constraintEnd_toEndOf="@+id/imageView2"
        app:layout_constraintStart_toStartOf="@+id/imageView2"
        app:layout_constraintTop_toBottomOf="@+id/imageView2" />

</androidx.constraintlayout.widget.ConstraintLayout>