Kotlin extension functions for Bitmaps

A collection of Kotlin extension methods that simplify many common tasks related to Bitmaps.

Loading and saving

fun Uri?.toBitmap(contentResolver: ContentResolver?): Bitmap? {
    if (this == null || contentResolver == null) return null
    return if (Build.VERSION.SDK_INT < 28) {
        MediaStore.Images.Media.getBitmap(
            contentResolver,
            this
        )
    } else {
        val source = ImageDecoder.createSource(contentResolver, this)
        ImageDecoder.decodeBitmap(source)
    }
}

fun Bitmap.writeToFile(file: File): File {
    val fOut = FileOutputStream(file)
    this.compress(Bitmap.CompressFormat.JPEG, 85, fOut)
    fOut.flush()
    fOut.close()
    return file
}

Resizing

/**
 * Resize bitmaps using new width value by keeping aspect ratio
 */
fun Bitmap.resizeByWidth(width: Int): Bitmap {
    val ratio: Float = this.width.toFloat() / this.height.toFloat()
    val height: Int = (width / ratio).roundToInt()

    return Bitmap.createScaledBitmap(
        this,
        width,
        height,
        false
    )
}

/**
 * Resize bitmaps using new height value by keeping aspect ratio
 */
fun Bitmap.resizeByHeight(height: Int): Bitmap {
    val ratio: Float = this.height.toFloat() / this.width.toFloat()
    val width: Int = (height / ratio).roundToInt()

    return Bitmap.createScaledBitmap(
        this,
        width,
        height,
        false
    )
}

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