DEV Community

rrtutors
rrtutors

Posted on • Originally published at rrtutors.com

Store Image in Sqlite Database

How to store Image in Sqlite in Android using the Room database
Create Room Database
Pick Image from Gallery
store Image and Contact info in the Sqlite database with Room Database.
Fetch Image from Sqlite Database and display it on Recyclerview

To store image in sqlite we need to convert image to bytes from the file and then store into sqlite database

val image = BitmapFactory.decodeFile(imagePath
            )
val stream = ByteArrayOutputStream()
            image.compress(Bitmap.CompressFormat.JPEG, 100, stream)
            val imageInByte: ByteArray = stream.toByteArray()

            MyDatabase.instance!!.contactsDAO().insert(Contact(name!!,imageInByte))
Enter fullscreen mode Exit fullscreen mode

Image to Sqlite Database

In the above code first we need to convert image to bitmap

val image = BitmapFactory.decodeFile(imagePath
            )
Enter fullscreen mode Exit fullscreen mode

Then From the bitmap we need to fetch bytearray

val stream = ByteArrayOutputStream()
            image.compress(Bitmap.CompressFormat.JPEG, 100, stream)
            val imageInByte: ByteArray = stream.toByteArray()

Enter fullscreen mode Exit fullscreen mode

Finally we need to insert butearray into database by insert query.

Discussion (0)