'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)
- I am not sure if
fun Int.toIconStringis the correct Extention, does not seem to have@IntegerReschecking therefore any Integer can be used - will cause a mess!!, How do I test and make sure its a Resource (Drawable)id: Int? - I am getting
android.content.res.Resources$NotFoundException: Resource ID #0x7f070075when using Methods A & B, even replacing theR.drawable.ic_twotone_fastfood_24directly into the Meathods instead of refering tothis! 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 |
|---|
