Convert files to base64 string to send as attachment through android application - android

I creating an application in which I am using mandrill app API to send emails. Emails without attachment are delivering, but when I attach image to it, it is received as damaged image at receiver side. Here it is required to convert file into base64 string to pass in json array. I used this code:
public static String encodeImagetoBase64(Bitmap img) {
Bitmap image = img;
ByteArrayOutputStream byteOStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteOStream);
byte[] b = byteOStream.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.e("Look", imageEncoded);
return imageEncoded;
}
So can anyone tell me the solution, why image is getting damaged.
Similarly I also want to convert files with extension ".txt,.doc,.docx,.pptx,.pdf,.xls" etc as attachment, so please suggest me any source for that. Thanx

I am using this method and it is working:
public static String getFileBinary(String uploadFilePath) {
String encodedString = "0";
if (uploadFilePath.length() < 2)
return encodedString;
try {
InputStream inputStream = new FileInputStream(uploadFilePath);//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();
encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
} catch (IOException es) {
}
return encodedString;
}

Related

split the video in few parts, encode each part in base64 in android

In my app I'm upload big size of video as base64 string form and it causes outofmemory error. There is one solution to prevent that is split the video in few parts, encode each part in base64 but I don't know how to do it as I'm not much experienced in android application development?
InputStream inputStream = null;
// Converting the video in to the bytes
try {
inputStream = getContentResolver().openInputStream(Uri.parse(String.valueOf(selectedMediaUri)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int len = 0;
try {
assert inputStream != null;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
String videoData = Base64.encodeToString(byteBuffer.toByteArray(), Base64.DEFAULT);
Instead of using Base64 use multipart for uploading a file, this will solve your problem.

Camera base64 image cannot be converted to Bitmap

I have been having trouble converting the base64 String Image that is being sent to me by the backend.
So this is how the backend sends the data.
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
And this is how we convert it.
final byte[] data = Base64.decode(base64, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(data, 0, data.length);
The result is always null. Any help is highly appreciated.
EDIT:
These are the back end codes.
#Override
public BufferedImage base64ToImage(String base64Image) throws IOException {
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
return img;
}
public static String imgToBase64String(final RenderedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString();
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
And this is our converting tool before sending the Base64 Image String to the back end.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);
Check that ur base64 encoded string does not start with data:image/jpg;base64,. If it does then remove it. The Base64.decode won't be able to decode it in this case. u can remove it by using encodedString.substring(encodedString.indexOf(",") + 1);. Let me know if this solves ur problem.
Try this,
ImageView driverImage = (ImageView) driverReportView.findViewById(R.id.imgViewDriverImage);
try {
byte [] encodeByte = Base64.decode(driverImageString.replace("\'/", "/"), Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
if (bitmap != null)
driverImage.setImageBitmap(bitmap);
}catch (Exception ex){
Log.e(TAG,"Error to display driver info "+ex.toString());
}
Where
driverImageString is your image string

How to convert a file to Base64?

Here the report contain the path(pathname in sdcard in string format)
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, report);
String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);
private static String encodeFileToBase64Binary(File fileName) throws IOException {
byte[] bytes = loadFile(fileName);
byte[] encoded = Base64.encodeBase64(bytes);
String encodedString = new String(encoded);
return encodedString;
}
in the byte[] encoded line getting this error.
The method encodeBase64(byte[]) is undefined for the type Base64
String value = Base64.encodeToString(bytes, Base64.DEFAULT);
But you can directly convert it in to String .Hope this will work for you.
An updated, more efficient, Kotlin version, that bypasses Bitmaps and doesn't store entire ByteArray's in memory (risking OOM errors).
fun convertImageFileToBase64(imageFile: File): String {
return ByteArrayOutputStream().use { outputStream ->
Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
imageFile.inputStream().use { inputStream ->
inputStream.copyTo(base64FilterStream)
}
}
return#use outputStream.toString()
}
}
I believe these 2 sample codes will help at least someone the same way many have helped me through this platform. Thanks to StackOverflow.
// Converting Bitmap image to Base64.encode String type
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
// Converting File to Base64.encode String type using Method
public String getStringFile(File f) {
InputStream inputStream = null;
String encodedFile= "", lastVal;
try {
inputStream = new FileInputStream(f.getAbsolutePath());
byte[] buffer = new byte[10240];//specify the size to allow
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
encodedFile = output.toString();
}
catch (FileNotFoundException e1 ) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
lastVal = encodedFile;
return lastVal;
}
I will be glad to answer any question regarding to these codes.
To convert a file to Base64:
File imgFile = new File(filePath);
if (imgFile.exists() && imgFile.length() > 0) {
Bitmap bm = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
String base64Image = Base64.encodeToString(bOut.toByteArray(), Base64.DEFAULT);
}
Convert Any file, image or video or text into base64
1.Import the below Dependancy
compile 'commons-io:commons-io:2.4'
2.Use below Code to convert file to base64
File file = new File(filePath); //file Path
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
for (int j = 0; j < b.length; j++) {
System.out.print((char) b[j]);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
} catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
byte[] byteFileArray = new byte[0];
try {
byteFileArray = FileUtils.readFileToByteArray(file);
} catch (IOException e) {
e.printStackTrace();
}
String base64String = "";
if (byteFileArray.length > 0) {
base64String = android.util.Base64.encodeToString(byteFileArray, android.util.Base64.NO_WRAP);
Log.i("File Base64 string", "IMAGE PARSE ==>" + base64String);
}
You can try this.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
...
byte[] byteArray = byteArrayOutputStream.toByteArray();
base64Value = Base64.encodeToString(byteArray, Base64.DEFAULT);
public static String uriToBase64(Uri uri, ContentResolver resolver, boolean thumbnail) {
String encodedBase64 = "";
try {
byte[] bytes = readBytes(uri, resolver, thumbnail);
encodedBase64 = Base64.encodeToString(bytes, 0);
} catch (IOException e1) {
e1.printStackTrace();
}
return encodedBase64;
}
private static byte[] readBytes(Uri uri, ContentResolver resolver, boolean thumbnail)
throws IOException {
// this dynamically extends to take the bytes you read
InputStream inputStream = resolver.openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
if (!thumbnail) {
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the
// byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
} else {
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
int thumb_width = imageBitmap.getWidth() / 2;
int thumb_height = imageBitmap.getHeight() / 2;
if (thumb_width > THUMBNAIL_SIZE) {
thumb_width = THUMBNAIL_SIZE;
}
if (thumb_width == THUMBNAIL_SIZE) {
thumb_height = ((imageBitmap.getHeight() / 2) * THUMBNAIL_SIZE)
/ (imageBitmap.getWidth() / 2);
}
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, thumb_width, thumb_height, false);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteBuffer);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
and call it in this way
String image = BitmapUtils.uriToBase64(Uri.fromFile(file), context.getContentResolver());

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 how to use it in android coding.
Will it reduce the size of an image?
Thanks in advance...
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);
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);
}

What is the most efficient way to convert image to Base64 in Android?

I am looking for the most efficient way of converting image file to Base64 String in Android.
The image has to be sent in a single Base64 String at once to backend.
First I use imageToByteArray and then imageToBase64 to get the String.
public static byte[] imageToByteArray(String ImageName) throws IOException {
File file = new File(sdcard, ImageName);
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
//Close input stream
is.close();
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
public String imageToBase64(String ImageName){
String encodedImage = null;
try {
encodedImage = Base64.encodeToString(imageToByteArray(ImageName), Base64.DEFAULT);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedImage;
}
Below is how I handle it mostly, this is in the gotActivityResults callback after calling the image picker activity. It's similar to your's but I think it will be more efficient because the toByteArray from the stream is native c code behind it as opposed to the java loop in yours.
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1= Base64.encodeToString(ba, 0);
HashMap<String, String > params = new HashMap<String, String>();
params.put("avatar", ba1);
params.put("id", String.valueOf(uc.user_id));
params.put("user_id", String .valueOf(uc.user_id));
params.put("login_token", uc.auth_token);
uc.setAvatar(params);

Categories

Resources