Rotate a Bitmap in an Android application

This tutorial explains how to rotate a bitmap in an Android application using Kotlin.

January 25, 2021 - 2 minute read -
Android Tutorial Kotlin

While it seems like an incredibly common piece of functionality, there’s no obvious rotateBitmap method included with the Android SDK. However, it’s trivial to write (or copy and paste) your own method, similar to the one below:

fun rotateBitmap(source: Bitmap, degrees: Float): Bitmap {
    val matrix = Matrix()
    matrix.postRotate(degrees)
    return Bitmap.createBitmap(
        source, 0, 0, source.width, source.height, matrix, true
    )
}

What’s happening here?

  • First, we’re creating a Matrix object, which is part of the android.graphics package. A Matrix holds a grid of transformation coordinates that can be applied to bitmaps and other graphics.

  • Rather than populating the grid manually, it has the method postRotate which accepts a degrees parameter.

  • A second bitmap is created using the static createBitmap method, passing in the original source bitmap along with our Matrix.

Since we want to rotate the entire bitmap, the 2nd and 3rd parameters can be set as 0, and the 4th and 5th parameters should be the source image width and height.

Usage

Typically, rotating an image would be used in more than one place within the application, so I would suggest putting the image-rotation logic into its own utility class.

object ImageRotationUtility {

    fun rotateBitmap(source: Bitmap, angle: Float): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(angle)
        return Bitmap.createBitmap(
            source, 0, 0, source.width, source.height, matrix, true
        )
    }
    
}

Then to rotate an image by 90 degrees:

val rotatedBitmap = ImageRotationUtility.rotateBitmap(source, 90f)