'Extention function to convert drawable to Bitmap and then to ByteArray

Purpose

I am storing small bitmaps in room/SQLlite and MongoDb as Strings. Therefore I need a few functions to convert them from String to Bitmap (png/jpg) and back.

Problem Description and Question(s)

  1. I am not sure if fun Int.toIconString is the correct Extention, does not seem to have @IntegerRes checking therefore any Integer can be used - will cause a mess!!, How do I test and make sure its a Resource (Drawable) id: Int?
  2. I am getting android.content.res.Resources$NotFoundException: Resource ID #0x7f070075 when using Methods A & B, even replacing the R.drawable.ic_twotone_fastfood_24 directly into the Meathods instead of refering to this! Why is the resource not found? as it exist in the project. Am I getting the resource correctly?

MyCode

fun Int.toIconString(): String {
    
    // Method A to convert the request R.drawable.ic_twotone_fastfood_24.toIconString()
    val myLogo: Bitmap = (ResourcesCompat.getDrawable(Resources.getSystem(), this, null) as BitmapDrawable?)!!.bitmap
    
    // Method B to convert the request R.drawable.ic_twotone_fastfood_24.toIconString()
    val mIcon: Bitmap = BitmapFactory.decodeResource(Resources.getSystem(), this, null)
    
    val imageIconString = Base64.encodeToString(
        mIcon.toByteArray(),  // Using Method B
        Base64.DEFAULT
    )
    Log.d(TAG, "Int.toIconString: $imageIconString")
    return imageIconString
}

// Extension function to convert bitmap to byte array
fun Bitmap.toByteArray(): ByteArray {
    ByteArrayOutputStream().apply {
        compress(Bitmap.CompressFormat.JPEG, 10, this)
        return toByteArray()
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source