how to upload image in base64 on server - android

i have a problem, i am uploading image on server but it is not. i have convert image in base64 and get through json. but json is not properly closed due to this i m getting error. error id om postimafe variable. in this variable {"key"""encode, here is json is not closed.
// code for convert base64
public static String getBase64String(String baseFileUri)
{
String encodedImageData = "";
try
{
System.out.println("getBase64String method is called :" +baseFileUri);
Bitmap bm = BitmapFactory.decodeFile(baseFileUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImageData = Base64.encodeToString(b, Base64.DEFAULT);
//ArrayList<NameValuePair> imagearraylistvalue = new ArrayList<NameValuePair>();
//imagearraylistvalue.add(new BasicNameValuePair("image", encodedImage));
System.out.println("encode data in upload file :" +encodedImageData );
}
catch(Exception ex)
{
System.out.println("Exception in getBase64String method in Utility class :" +ex);
}
return encodedImageData ;
}
// code for json and uplod base64 to server but i m getting error
System.out.println("fullupload image for 1:" +fulluploadimgpath);
String base64String = Utility.getBase64String(fulluploadimgpath);
System.out.println("base64String is in :" +base64String);
if (base64String != null)
{
JSONObject postImageData = new JSONObject();
postImageData.put("media",base64String);
System.out.println("post image :" +postImageData);
HttpResponse imgPostResponse = Utility.postDataOnUrl(Utility.getBaseUrl()+"user/upload",obj.toString());
System.out.println("fullupload image for imgPostResponse:" +imgPostResponse);
if (imgPostResponse != null)
{
String imgResponse = Utility.readUrlResponseAsString(imgPostResponse);
System.out.println("imgResponse is in imgResponse :" +imgResponse);
if (imgResponse != null|| imgResponse.trim().length() != 0)
{
JSONObject jResObj = new JSONObject();
if (jResObj.getBoolean("rc"))
{
obj.put(hidobj.getReceiveAs(),jResObj.getLong("ident"));
}
}

String encodedImageData =getEncoded64ImageStringFromBitmap(your bitmap);
public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// get the base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}

Related

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

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

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;
}

base64 string is not uploaded in server android?

I need to send the image (from gallery) to server in the format of base64 string. I get the path of the image and converted it to base64 string. but at server the image is not showing fully. only 10% of the image is showing at server side.Please any one help me how to convert the image to base64 string.
code:
filePath = cursor.getString(columnIndex);
Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(CompressFormat.PNG, 100, bao);
byte [] ba = bao.toByteArray();
ba1 =Base64.encodeToString(ba, Base64.DEFAULT);
image size:460kb
try with this i hope it will work for you and send using httpPost method.
public static String BitmapToString(Bitmap bmp) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
return base64;
}
and server side.
Base64 base64=new Base64();
saveImage(base64.decode(profilePic),"yourName");
public void saveImage(byte[] bytes,String name){
String path="D:/"+name.hashCode()+".png";
try {
FileOutputStream f = new FileOutputStream(path);
f.write(bytes);
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}

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());

Add Convert to JSONObject

I'm trying to figure out how to add the following data to my json object. Could someone show me how to do this.
{
"main_img":"Base64 String"
}
However, the following is the result of using this code, to come out.
final int COMPRESSION_QUALITY = 100;
String encodedImage;
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY,
byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
encodedImage = "data:image/JPEG;base64," + Base64.encodeToString(b, Base64.DEFAULT);
JSONObject jObject = new JSONObject();
jObject.put("main_img", result);
{
"main_img":"Base64 String
It is displayed with }, " is missing.

Categories

Resources