Convert Images to Base64Just select your JPG, PNG, GIF, Webp, or BMP picture or drag & drop it in the form below, press the Convert to Base64 button, and you'll get a base-64 string of the image. Press a button – get base64. No ads, nonsense, or garbage. Drag and drop your image here!
String img=o. toString(); byte[] imageAsBytes = Base64. decode(img. getBytes(), Base64.
Right click on an image preview within the Resources Panel to copy it as a Data URI which is base 64 encoded. As a bonus tip, you can base 64 encode an image from the terminal also, without DevTools.
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 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 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);
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.
// Put the image file path into this method
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}
catch (Exception e){
e.printStackTrace();
}
return encodeString;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With