添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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

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);