Android: Encode & Decode Base64
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
Solution 1:
To encode any file:
private String encodeFileToBase64(String filePath)
{
InputStreaminputStream=newFileInputStream(filePath);//You can get an inputStream using any IO APIbyte[] bytes;
byte[] buffer = newbyte[8192];
int bytesRead;
ByteArrayOutputStreamoutput=newByteArrayOutputStream();
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);
Solution 2:
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:
publicstaticStringgetBase64(Bitmap bitmap)
{
try{
ByteArrayOutputStream byteArrayOutputStream = newByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
returnBase64.encodeToString(byteArray, Base64.NO_WRAP);
}
catch(Exception e)
{
returnnull;
}
}
publicstaticBitmapgetBitmap(String base64){
byte[] decodedString = Base64.decode(base64, Base64.NO_WRAP);
returnBitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
Post a Comment for "Android: Encode & Decode Base64"