How can I convert an image into a Base64 string? How can I convert an image into a Base64 string? android android

How can I convert an image into a Base64 string?


You can use the Base64 Android class:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

You'll have to convert your image into a byte array though. Here's an example:

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");ByteArrayOutputStream baos = new ByteArrayOutputStream();bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap objectbyte[] b = baos.toByteArray();

* Update *

If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 AKA version 2.2).

Check this article out for a workaround:

How to base64 encode decode Android


Instead of using Bitmap, you can also do this through a trivial InputStream. Well, I am not sure, but I think it's a bit efficient.

InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O APIbyte[] bytes;byte[] buffer = new byte[8192];int bytesRead;ByteArrayOutputStream output = new ByteArrayOutputStream();try {    while ((bytesRead = inputStream.read(buffer)) != -1) {        output.write(buffer, 0, bytesRead);    }}catch (IOException e) {    e.printStackTrace();}bytes = output.toByteArray();String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);


If you need Base64 over JSON, check out Jackson: it has explicit support for binary data read/write as Base64 at both the low level (JsonParser, JsonGenerator) and data-binding level. So you can just have POJOs with byte[] properties, and encoding/decoding is automatically handled.

And pretty efficiently too, should that matter.