0

How to encode and decode any image from base64 format.

I donno anything about base64, just now I came to know that it saves image in String format. Please explain about base64 and how to use it in android coding. Will it reduce the size of an image?

Thanks in advance...

  • possible duplicate of [How to convert a image into Base64 string?](http://stackoverflow.com/questions/4830711/how-to-convert-a-image-into-base64-string) – Ben Pearson Sep 05 '14 at 18:38

2 Answers2

1

To encode any file:

private String encodeFileToBase64(String filePath)
{
    InputStream inputStream = new FileInputStream(filePath);//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();
    return Base64.encodeToString(bytes, Base64.DEFAULT);
}

Decode:

byte[] data = Base64.decode(base64, Base64.DEFAULT);
Sagar Pilkhwal
  • 5,825
  • 2
  • 24
  • 76
  • It just transforms a file into its base64 representation, and avoids an absolutely meaningless recompression of the image. – Sagar Pilkhwal Sep 05 '14 at 18:53
  • 1
    I used Base64.NO_WRAP instead of Base64.DEFAULT and it gives the same output as http://freeonlinetools24.com/base64-image great! – Juan Rojas Jan 03 '19 at 17:03
0

Base64 allows you to represent binary data in ASCII format, You can use it for send/receive images to an endpoint

To encode/decode check this two methods:

public static String getBase64(Bitmap bitmap)
{
    try{
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();

        return Base64.encodeToString(byteArray, Base64.NO_WRAP);
    }
    catch(Exception e)
    {
        return null;
    }
}

public static Bitmap getBitmap(String base64){
    byte[] decodedString = Base64.decode(base64, Base64.NO_WRAP);
    return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
Ariel Carbonaro
  • 1,429
  • 1
  • 14
  • 25