Android Kotlin: ImageView grayscale filter

This code demonstrates applying a grayscale filter to an ImageView in Android using Kotlin.

The code consists of the following parts:

  • MainActivity class: This is the main class of the application. It inherits from the Activity class and overrides the onCreate() method. The onCreate() method is called when the activity is first created. In this code, it performs the following steps:

    • Sets the layout of the activity using setContentView(R.layout.activity_main).
    • Gets references to the ImageView widgets from the layout using findViewById().
    • Loads a bitmap image from the assets folder using the assetsToBitmap() extension function.
    • Sets the bitmap to the first ImageView.
    • Creates a copy of the bitmap and applies a grayscale filter to it using the toGrayscale() extension function.
    • Sets the filtered bitmap to the second ImageView.
  • assetsToBitmap() extension function: This extension function takes a filename as input and attempts to open the corresponding file from the assets folder. If successful, it decodes the file into a Bitmap object and returns it. Otherwise, it catches any IOException and prints an error message.

  • toGrayscale() extension function: This extension function takes an ImageView as input. It creates a ColorMatrix object and sets its saturation to 0 (which converts the image to grayscale). Finally, it creates a ColorMatrixColorFilter object from the ColorMatrix and sets it as the color filter of the ImageView.

  • activity_main.xml: This is the layout file of the activity. It defines the UI elements of the activity, including two ImageViews and two TextViews.

Overall, this code effectively demonstrates how to load an image from the assets folder, apply a grayscale filter to it, and display both the original and filtered images in separate ImageViews within an Android application.

Here's a table summarizing the key parts of the code:

PartDescription
MainActivity classThe main class of the application
onCreate() methodSets up the activity and applies the grayscale filter to the image
assetsToBitmap() extension functionLoads a bitmap image from the assets folder
toGrayscale() extension functionApplies a grayscale filter to an ImageView
activity_main.xmlThe layout file of the activity

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
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)


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


        bitmap?.apply {
            // set bitmap to first image view
            imageView.setImageBitmap(this)

            // set second image view image and filter it gray scale
            imageView2.setImageBitmap(this)
            imageView2.toGrayscale()
        }
    }
}



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



// extension function to image view grayscale filter
fun ImageView.toGrayscale(){
    val matrix = ColorMatrix().apply {
        setSaturation(0f)
    }
    colorFilter = ColorMatrixColorFilter(matrix)
}
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:background="#DCDCDC"
    android:padding="24dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="250dp"
        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" />

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

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

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials