Search code examples
androidkotlincolorsbitmap

manipulate the colours in a Bitmap android


I have a QrCode which i want to change its colours to white and blue... I can do it using the following code:

val bitmap = qrgEncoder.encodeAsBitmap()
        val width = bitmap.width
        val height = bitmap.height
        // All are 0, or black, by default
        for (y in 0 until height) {
            for (x in 0 until width) {
                bitmap.getPixel(x, y).also {
                    if(it != -1)
                        bitmap.setPixel(x, y, ResourcesCompat.getColor(resources, R.color.defaultTextColor, null))
                    else
                        bitmap.setPixel(x, y, ResourcesCompat.getColor(resources, R.color.toolbarColor, null))
                }
            }
        }
        // Setting Bitmap to ImageView
        qrImage.setImageBitmap(bitmap)

but this is too slow... so I am wondering what is the best approach to do the same thing and faster.


Solution

  • After trying different solutions, I realised the only way is to manipulate the pixels. The following code is the optimum solution for now:

    val pixelsArray = IntArray(mWidth * mHeight)
    val newColor1 = getColor(context!!, R.color.color1)
    val newColor2 = getColor(context!!, R.color.color2)
    bitmap.getPixels(pixelsArray, 0, mWidth, 0, 0, mWidth, mHeight)
    for (y in 0 until pixelsArray.size) {
        if (pixelsArray[y] != -1)
            pixelsArray[y] = newColor1
        else
        pixelsArray[y] = newColor2
    }