From Bitmap To Base64 And Back With Native Android

Working with images in Android is great, but what happens when you need to store them somewhere other than the file system? Let’s say for example you want to store them in a SQLite or NoSQL type database. How would you store such a piece of data?

One common way to store image data would be to first convert the image into a base64 string. We all know strings are very easy to store in some data structure.

A group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

Another way would be to store the binary data in a CLOB or BLOB type SQL column, but to keep it generic, in this particular example, we will be exploring the idea of converting images into base64 strings.

In Android, it is common to use the Bitmap class for anything related to images. Images downloaded from the internet can be stored as a bitmap and likewise with images taken from the device camera.

To convert an image from bitmap to base64 you can use a function like the following:

The above code will take a base64 string and convert it back into a bitmap.

Conclusion

It is not too bad converting between the bitmap and base64 format and depending on what you’re trying to do, this can prove quite useful. If you absolutely don’t want to store the image data on a filesystem, you can just store the base64 string in a database instead.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.