Tuesday, April 17, 2018

android kotlin - Convert JPG to PNG to WebP programmatically

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.ByteArrayOutputStream
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)
        }


        // Click listener for button widget
        button.setOnClickListener{
            if(bitmap!=null){
                // Compress bitmap and convert image format from one to another
                val compressedBitmap = bitmap.compress(Bitmap.CompressFormat.PNG)
                //val compressedBitmap = bitmap.compress(Bitmap.CompressFormat.WEBP)

                //val compressedBitmap = bitmap.compress(Bitmap.CompressFormat.JPEG)
                //val compressedBitmap = bitmap.compress(Bitmap.CompressFormat.JPEG, 10)
                //val compressedBitmap = bitmap.compress(quality = 10) // Compress only


                // Display the compressed bitmap into image view
                image_view_compressed.setImageBitmap(compressedBitmap)

                // Notify user
                text_view.text = "Bitmap format changed."
            }else{
                // Log error
            }
        }
    }


    // 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
        }
    }
}


// Extension function to compress and change bitmap image format programmatically
fun Bitmap.compress(format:Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG, quality:Int = 100):Bitmap{
    // Initialize a new ByteArrayStream
    val stream = ByteArrayOutputStream()

    /*
        **** reference source developer.android.com ***

        public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)
            Write a compressed version of the bitmap to the specified outputstream.
            If this returns true, the bitmap can be reconstructed by passing a
            corresponding inputstream to BitmapFactory.decodeStream().

            Note: not all Formats support all bitmap configs directly, so it is possible
            that the returned bitmap from BitmapFactory could be in a different bitdepth,
            and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels).

            Parameters
            format : The format of the compressed image
            quality : Hint to the compressor, 0-100. 0 meaning compress for small size,
                100 meaning compress for max quality. Some formats,
                like PNG which is lossless, will ignore the quality setting
            stream: The outputstream to write the compressed data.

            Returns
                true if successfully compressed to the specified stream.


        Bitmap.CompressFormat
            Specifies the known formats a bitmap can be compressed into.

                Bitmap.CompressFormat  JPEG
                Bitmap.CompressFormat  PNG
                Bitmap.CompressFormat  WEBP
    */

    // Compress the bitmap with JPEG format and quality 50%
    this.compress(
            format,
            quality,
            stream
    )

    val byteArray = stream.toByteArray()

    // Finally, return the compressed bitmap
    return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
}
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="#99b196"
    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"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert JPEG To PNG"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        />
    <ImageView
        android:id="@+id/image_view_compressed"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="center"
        />
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textStyle="bold"
        android:layout_margin="10dp"
        />
</LinearLayout>