Monday, April 16, 2018

android kotlin - Resize bitmap keep 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
                val resizedBitmap = bitmap.resizeByWidth(900)
                //val resizedBitmap = bitmap.resizeByHeight(400)

                // 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 function to resize bitmap using new width value by keeping aspect ratio
fun Bitmap.resizeByWidth(width:Int):Bitmap{
    val ratio:Float = this.width.toFloat() / this.height.toFloat()
    val height:Int = Math.round(width / ratio)

    return Bitmap.createScaledBitmap(
            this,
            width,
            height,
            false
    )
}


// Extension function to resize bitmap using new height value by keeping aspect ratio
fun Bitmap.resizeByHeight(height:Int):Bitmap{
    val ratio:Float = this.height.toFloat() / this.width.toFloat()
    val width:Int = Math.round(height / ratio)

    return Bitmap.createScaledBitmap(
            this,
            width,
            height,
            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="#9798fd"
    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="Resize Bitmap"
        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>