nutella_eater
nutella_eater

Reputation: 3582

How to properly grayscale bitmap on android to make the file lighter

I'm trying to get the most out of compression and I need to make my image grayscale in order to make the file lighter. I found a function that makes image grayscale:

fun toGrayscale(bmpOriginal: Bitmap): Bitmap {
        val width = bmpOriginal.width
        val height = bmpOriginal.height

        val bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val c = Canvas(bmpGrayscale)
        val paint = Paint()
        val cm = ColorMatrix()
        cm.setSaturation(0f)
        val f = ColorMatrixColorFilter(cm)
        paint.colorFilter = f
        c.drawBitmap(bmpOriginal, 0f, 0f, paint)
        return bmpGrayscale
}

Then I save it with

try {
    FileOutputStream(filePathGrayScale).use { out ->
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, out)
    }
} catch (e: IOException) {
    e.printStackTrace()
}

But the image size increase!

What exactly I'm doing wrong and how to make the thing correct?

Upvotes: 0

Views: 397

Answers (1)

RobCo
RobCo

Reputation: 6505

bmp.compress(Bitmap.CompressFormat.JPEG, 100, out)

You are saving the image with an compression quality of 100. This maximizes file size (and minimizes quality loss).

If you want to make the most of compression, pass a lower value here. There is no ideal value because it really depends on the image being compressed and the tolerable amount of artefacts. It's a trade-of between file size and image quality.

For some more reading about the quality level see:
What quality to choose when converting to JPG?
And some examples 1, 2

Upvotes: 1

Related Questions