Android Kotlin: Bitmap to byte array

Introduction

This Android Kotlin code demonstrates how to create a byte array from a Bitmap object. The code utilizes several techniques, including working with bitmaps, converting between byte arrays and bitmaps, and using extension functions.

Breaking Down the Code

  1. MainActivity.kt

    • The MainActivity class inherits from the Activity class, which is the foundation for most Android activities.
    • The onCreate method is called when the activity is first created.
    • Inside onCreate, the code fetches references to two ImageViews (imageview and imageview2) and a textview from the activity's layout using findViewById.
    • The assetsToBitmap extension function is used to load a bitmap from the app's assets folder. This function takes the filename of the image as input and returns a Bitmap object if successful.
    • The loaded bitmap is then assigned to both imageView and imageView2.
    • The toByteArray extension function is called on the bitmap to convert it into a byte array. This function utilizes a ByteArrayOutputStream to compress the bitmap into a JPEG format with a quality of 10 (out of 100). The compressed data is then retrieved as a byte array.
    • Finally, the toBitmap extension function is called on the byte array to convert it back into a Bitmap object. This bitmap is then set to imageView2.
  2. Extension Functions

    • The code utilizes three extension functions:
      • assetsToBitmap(fileName: String): Bitmap? This function retrieves a bitmap from the assets folder using the provided filename. It returns a Bitmap object if successful or null if an error occurs.
      • toByteArray(): ByteArray This extension function converts a Bitmap object into a byte array. It utilizes ByteArrayOutputStream to compress the bitmap into a byte array.
      • toBitmap(): Bitmap This extension function converts a byte array back into a Bitmap object.
  3. activity_main.xml

    • The activity_main.xml file defines the layout for the activity. It contains two ImageViews and two TextViews.
      • The first ImageView (imageView) is used to display the original bitmap loaded from assets.
      • The second ImageView (imageView2) is used to display the bitmap after it has been converted to a byte array and then back to a bitmap.
      • The TextViews are used to label the ImageViews.

Summary

This code demonstrates a straightforward approach to converting a Bitmap object into a byte array and then back into a Bitmap in Android using Kotlin. The code leverages extension functions to enhance readability and code maintainability. By understanding how to work with bitmaps and byte arrays, developers can perform various image processing tasks within their Android applications.


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.ByteArrayOutputStream
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
        val bitmap = assetsToBitmap("flower103.jpg")

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

            // show bitmap to byte array to bitmap in second image view
            imageView2.setImageBitmap(toByteArray().toBitmap())
        }
    }
}


// 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 convert bitmap to byte array
fun Bitmap.toByteArray():ByteArray{
    ByteArrayOutputStream().apply {
        compress(Bitmap.CompressFormat.JPEG,10,this)
        return toByteArray()
    }
}


// extension function to convert byte array to bitmap
fun ByteArray.toBitmap():Bitmap{
    return BitmapFactory.decodeByteArray(this,0,size)
}
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"
    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: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:text="Bitmap To ByteArray To Bitmap"
        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