Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

From Bitmap To Base64 And Back With Native Android

TwitterFacebookRedditLinkedInHacker News

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.

Base64 via Wikipedia:

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:

private String bitmapToBase64(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream .toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

In the above code you are getting the image as an array of bytes and then encoding the array of bytes into a base64 string.

With this string, you can store it anywhere you choose, but what happens when you want to convert it back into a useable format?

private Bitmap base64ToBitmap(String b64) {
    byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}

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

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