How to convert a image into Base64 string?


Question

Can someone tell me the code to transform a image (maximum of 200KB) into Base64 String?

I need to know how to do it with android, because I have to add the functionality to upload images to a remote server in my main app putting them into a row of the database, as a string.

I am searching in google and in StackOverflow but I could not find easy examples that I can afford and also I find some examples but they are not talking about to transform into String. Then I need to transform into string to upload by JSON to my remote server.

1
136
1/5/2014 7:26:45 PM

Accepted Answer

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 object   
byte[] 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 work-around:

http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html

314
3/7/2012 7:24:24 AM

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

InputStream inputStream = new FileInputStream(fileName);//You can get an inputStream using any IO API
byte[] 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);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon