Saturday, June 20, 2020

android kotlin - Base64 string to bitmap

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.Base64
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 textView = findViewById<TextView>(R.id.textView)

        // make text view text scrollable
        textView.movementMethod = ScrollingMovementMethod()

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

        bitmap?.apply {
            // encode this bitmap to base64 string
            val base64String = toBase64String()

            // show base64 string of bitmap
            textView.text = base64String

            // decode base64 string to bitmap
            val decodedBitmap:Bitmap? = base64String.toBitmap()

            // show decoded bitmap in image view
            imageView.setImageBitmap(decodedBitmap)
        }
    }
}


// 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 encode bitmap to base64 string
fun Bitmap.toBase64String():String{
    ByteArrayOutputStream().apply {
        compress(Bitmap.CompressFormat.JPEG,90,this)
        return Base64.encodeToString(toByteArray(),Base64.DEFAULT)
    }
}


// extension function to decode base64 string to bitmap
fun String.toBitmap():Bitmap?{
    Base64.decode(this,Base64.DEFAULT).apply {
        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"
    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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:fontFamily="sans-serif"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text=" Base64 String" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="250dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>