Skip to main content

android kotlin - Compress bitmap example

Compress Bitmap
The bitmap is used to display an image on ImageView. Sometimes android developers have to compress a Bitmap object before displaying it on the ImageView widget. The following android application development tutorial will demonstrate to us how we can compress a bitmap in an application. We used the Kotlin programming language to write the code for this tutorial.

In this tutorial XML layout file, we put two ImageView widgets, a Button widget, and a TextView widget. The first ImageView widget displays the original uncompressed bitmap on its surface. In the Button’s click event, we programmatically compress the bitmap instance. On the second ImageView widget, we displayed the compressed bitmap after applying compression with a specified quality value/percentage. The TextView widget displays the applied compression quality value/percentage on it.

So, how we can compress a bitmap object programmatically using the native android SDK API? To do that first we create a ByteArrayOutputStream instance. The ByteArrayOutputStream implements an output stream in which the data is written into a byte array. The data can be retrieved using the toByteArray() and toString() methods.

Next, we call the Bitmap compress() method. The bitmap compress() method writes a compressed version of the bitmap to the specified outputstream. This method takes three arguments, that are format, quality, and stream. The ‘format’ argument represents the format of the compressed bitmap. We can set this argument value using CompressFormat enum values. The available formats are JPEG, PNG, WEBP, WEBP_LOSSLESS, and WEBP_LOSSY.

The ‘quality’ argument is an int value that range is 0 to 100. This defines the compression quality. We can call it the percentage of compression quality. And the ‘stream’ is the outputstream to write the compressed data. The compress() method returns true if it is successfully compressed to the specified stream. Finally, we get the compressed bitmap using the BitmapFactory API.

This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to see how we can compress a bitmap programmatically in an android application. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import java.io.ByteArrayOutputStream
import kotlin.random.Random


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the widgets reference from XML layout
        val button = findViewById<Button>(R.id.button)
        val ivCompressed = findViewById<ImageView>(R.id.ivCompressed)
        val textView = findViewById<TextView>(R.id.textView)

        // Get the bitmap from given drawable object
        val drawable = ContextCompat.getDrawable(
            applicationContext,R.drawable.rose)
        val bitmap = (drawable as BitmapDrawable).bitmap

        // Click listener for button widget
        button.setOnClickListener{
            val quality = Random.nextInt(2,10)

            // Compress bitmap and display into image view
            ivCompressed.setImageBitmap(
                compressBitmap(bitmap,quality)
            )
            textView.text = "Compressed bitmap (quality $quality)"
        }
    }


    // Method to compress a bitmap
    private fun compressBitmap(bitmap: Bitmap, quality:Int):Bitmap{
        // Initialize a new ByteArrayStream
        val stream = ByteArrayOutputStream()

        // Compress the bitmap with JPEG format and specified quality
        bitmap.compress(
            Bitmap.CompressFormat.JPEG, 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"?>
<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="8dp">

    <ImageView
        android:id="@+id/ivSource"
        android:layout_width="match_parent"
        android:layout_height="225dp"
        android:src="@drawable/rose"
        android:scaleType="centerCrop"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        android:layout_marginTop="12dp"
        android:text="Compress The Bitmap"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ivSource" />

    <ImageView
        android:id="@+id/ivCompressed"
        android:layout_width="match_parent"
        android:layout_height="225dp"
        android:layout_marginTop="12dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ivCompressed" />

</androidx.constraintlayout.widget.ConstraintLayout>

Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...