Tuesday, April 17, 2018

android kotlin - Bitmap scale down with aspect ratio

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.graphics.Bitmap
import android.widget.Toast
import android.graphics.BitmapFactory
import java.io.IOException


class MainActivity : AppCompatActivity() {

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

        // Get the bitmap from assets and display into image view
        val bitmap = assetsToBitmap("flower7.jpg")
        // If bitmap is not null
        bitmap?.let {
            image_view_bitmap.setImageBitmap(bitmap)

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


        // Click listener for button widget
        button.setOnClickListener{
            if(bitmap!=null){
                // Resize the bitmap by keeping aspect ration
                // Bitmap scaled to given maximum height and width value
                val resizedBitmap = bitmap.scale(500)

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

                // Display the resized bitmap's width and height
                text_view_resized.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"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root_layout"
    android:background="#a2a960"
    android:padding="16dp"
    android:orientation="vertical"
    >
    <ImageView
        android:id="@+id/image_view_bitmap"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="center"
        />
    <TextView
        android:id="@+id/text_view_bitmap"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textStyle="bold"
        android:layout_margin="10dp"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Scale Bitmap To Max Width And Height"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        />
    <ImageView
        android:id="@+id/image_view_file"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="center"
        />
    <TextView
        android:id="@+id/text_view_resized"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textStyle="bold"
        android:layout_margin="10dp"
        />
</LinearLayout>