Sunday, April 15, 2018

android kotlin - Resize a bitmap

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("tulip.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 and display it into image view
                val resizedBitmap = resizeBitmap(bitmap,600,600)
                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
        }
    }



    // Method to resize a bitmap programmatically
    private fun resizeBitmap(bitmap:Bitmap, width:Int, height:Int):Bitmap{
        /*
            *** reference source developer.android.com ***
            Bitmap createScaledBitmap (Bitmap src, int dstWidth, int dstHeight, boolean filter)
                Creates a new bitmap, scaled from an existing bitmap, when possible. If the specified
                width and height are the same as the current width and height of the source bitmap,
                the source bitmap is returned and no new bitmap is created.

            Parameters
                src Bitmap : The source bitmap.
                    This value must never be null.

            dstWidth int : The new bitmap's desired width.
            dstHeight int : The new bitmap's desired height.
            filter boolean : true if the source should be filtered.

            Returns
                Bitmap : The new scaled bitmap or the source bitmap if no scaling is required.

            Throws
                IllegalArgumentException : if width is <= 0, or height is <= 0
        */
        return Bitmap.createScaledBitmap(
                bitmap,
                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="#d8f1cb"
    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>