Android Kotlin: Bitmap color filter

Applying Color Filters to Bitmaps in Android with Kotlin

This code demonstrates applying a color filter to a Bitmap in an Android application written in Kotlin. It utilizes two key components:

  1. Extension functions: The code defines two extension functions that enhance readability and code reusability.

    • assetsToBitmap(fileName:String): This function retrieves a Bitmap from the app's assets folder, handling potential exceptions.
    • colorFilter(color:Int, mode:PorterDuff.Mode): This function applies a color filter using PorterDuff blending mode to a Bitmap, returning a new filtered Bitmap.
  2. PorterDuffColorFilter: The code leverages PorterDuffColorFilter to apply color manipulation effects. It takes two arguments: target color and blending mode.

Code Breakdown

The MainActivity class manages the core functionality:

  1. Setting Up UI elements: It retrieves references to ImageViews and TextViews from the activity's layout file (activity_main.xml).
  2. Loading Bitmap: It loads a bitmap named "flower2.jpg" from the assets folder using the assetsToBitmap extension function.
  3. Displaying Original Bitmap: The original bitmap is displayed on the first ImageView.
  4. Applying Color Filter and Displaying: The colorFilter extension function is used to create a new Bitmap with a color filter applied (green color with DARKEN mode by default). This filtered bitmap is then displayed on the second ImageView. Additionally, a TextView displays information about the applied filter.

The provided activity_main.xml defines the layout for the activity, consisting of two ImageViews to display the bitmaps and two TextViews to provide labels.


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)


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


        bitmap?.apply {
            // show original bitmap in first image view
            imageView.setImageBitmap(this)

            // show color filtered bitmap on second image view
            imageView2.setImageBitmap(colorFilter(
                Color.parseColor("#ACE1AF"),
                PorterDuff.Mode.MULTIPLY
            ))
            textView2.text = "PorterDuffColorFilter (#ACE1AF, MULTIPLY)"
        }
    }
}



// extension function to get 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 apply porter duff color filter in bitmap
fun Bitmap.colorFilter(
    color:Int = Color.GREEN,
    mode:PorterDuff.Mode = PorterDuff.Mode.DARKEN
):Bitmap?{
    val bitmap = copy(Bitmap.Config.ARGB_8888,true)
    Paint().apply {
        val filter =  PorterDuffColorFilter(color,mode)
        colorFilter = filter
        Canvas(bitmap).drawBitmap(this@colorFilter,0f,0f,this)
    }
    return bitmap
}
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="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="Bitmap Color Filtered"
        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