This won't be effective for large images. You don't want megabytes of data in each row of your database. If the images are large, save them as files and put just the file names in your database.
But assuming these are tiny images:
Follow the instructions here for using type converters with your database. Based on the answer here and translating it, we get the following functions.
class Converters {
@TypeConverter
fun stringToBitmap(value: String?): Bitmap? {
value ?: return null
val bytes = Base64.decode(value, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
if (bitmap == null) {
Log.e("stringToBitmap converter", "Failed to decode image.")
}
return bitmap
}
@TypeConverter
fun bitmapToString(bitmap: Bitmap?): String? {
bitmap ?: return null
val stream = ByteArrayOutputStream()
if (!bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream)) {
Log.e("bitmapToString converter", "Failed to compress image.")
return null
}
return Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT)
}
}
>?`** i.e. the type of of **image** field rather than part of the type. Thus the TypeConverter pair expected should convert from/to a **`List
– MikeT Jul 30 '23 at 04:58>?`** not just a **`Bitmap`**.