Android: Recover image bitmap from representation as decoded string [duplicate] - android

In Java server I fetch image from external service URL like:
InputStream in = new java.net.URL(imageWebServiceURL).openStream();
String resultToCleint = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(IOUtils.toByteArray(in));
Then on Android I parse it like:
byte[] imageAsBytes = Base64.decode(resultToCleint.getBytes(), Base64.DEFAULT);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
Result: Image not displayed, ain't errors/exceptions neither on server nor on client.
What is the problem here?
EDIT: On android I use class android.util.Base64
Thanks,

Use Picasso library to load image:
You just need to add 1 line of code to show the image on ImageView
//Loading image from below url into imageView
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.into(imageView);
You can learn more from here

use this to convert to base 64
public static String uploadPic(Bitmap bm) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = ""+ Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
check if image is uploaded then using volley String request object download the string response using this code convert it back.
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}

As commented, let's assume base64Content is the base64 string responsed from your web service/server-side app, you can refer to the following sample code:
String base64Content = jsonObject.getString("Base64Content");
byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Moreover, if your server compressed reponse data either by gzip or deflate, your client app must decompress the data first.
Hope this helps!

Related

How to convert Bitmap into Base64 String without compressing? [duplicate]

This question already has an answer here:
How to convert a image into Base64 string without compressing the image?
(1 answer)
Closed 3 years ago.
I am trying to convert a bitmap image into base64 String using this code. I and getting a very low-quality image. How can I get a good quality image after convert bitmap into Base64 Sring
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
base64Image = Base64.encodeToString(b, Base64.DEFAULT);
return base64Image;
}
If I have a 5MB image. After convert, I am getting the only 160KB image. But in my case, I don't want to compress my image too much I just want to get Base64 String based on Bitmap image only JPEG format, not any other. Please help me with this.
Try this:
public String getBase64Image(Bitmap bitmap) {
try {
ByteBuffer buffer =
ByteBuffer.allocate(bitmap.getRowBytes() *
bitmap.getHeight());
bitmap.copyPixelsToBuffer(buffer);
byte[] data = buffer.array();
return Base64.encodeToString(bytes, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

how to show Base64 encoded image string in ImageView

I am picking an image from gallery and converting into Base64 encoded string and sending to server
Below code for conversion to Base64:
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
But when I get encoded String from server it don't get displayed in ImageView
Base64 encoded image string below:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAi8CLwDASIA
AhEBAxEB/8QAHwAAAAYDAQEBAAAAAAAAAAAAAgMEBQYHAQgJAAoL/8QAUxAAAgICAQMEAQMDAwMB
AQAjAQIDEQQSBQYhIgAHEzEIFDJBI0JRCRVhFlJxM2IKFyRygUORGCWCoTRTkqKxJsHRGWPwwvEa
J7LhNTZEc5PS8v/EABwBAAIDAQEBAQAAAAAAAAAAAAIDAAEEBQYHCP/EAEsRAAIBAgUCBAMHAgUD
AwIADwERAiExAAMSQVEEYQUicYEykaEGE0JSscHwYtEUc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49gybKWCEAHuBa/ZAX9zqdTTErYY
+djpACCpU332oLdhQCp3vY9lYggCipHdfWY11VQ9hlUhKBKhQbVAbIYhvMMfuxqSO58pA2DXtRAq
2JTuYzRZAG2A7WCwNXSqTQjclRJlWVRwRR/xWdqhATkzJ2MRUgIAVFPU8r5jhRnjOxEYDswYEsAo
Ozgq9hlvVu/aiGIHrMrByERgEa1ZlCsr/wAFLpwrkldaP23agGBDGSpWJd9WYaFygYKC+yagFiuh
Ut5XY7lvsiZNSg12VhsdCaCsA
and i display this encode image string in ImageView like this
String imageDataBytes = path;
InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.URL_SAFE));
Bitmap image = BitmapFactory.decodeStream(stream);
dashboard_img.setImageBitmap(image);
Above code I use Base.64URL_SAFE and Default also but not working. So please help me to fix this
Try this
Bitmap bmp = BitmapFactory.decodeByteArray(yourBase64String, 0, yourBase64String.length);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, customWidth, customHeight, false));
Refresh imageview with invalidate. Use this code snippet
try {
byte[] decodedString = Base64.decode(imageDataBytes, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
dashboard_img.setImageBitmap(bitmap);
dashboard_img.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
Edit:
I have checked your base64 string it is not a valid base 64.
For set base64 image in imageView you can follow given code:
String filePath;
Bitmap bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), Uri.parse(filePath)); // filePath is our BASE64 string
imgView.setImageBitmap(bm);
And in-case your base64 string may be wrong, because this also can not decode on online decoder : https://www.base64decode.org/

200kb image to base64 cannot send to web service

I got bad request 400 when i send base64 image in the web service,
I put base64 string to JSON and POST it using retrofit. here is my code
Bitmap bm = BitmapFactory.decodeFile("IMAGE PATH");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String imgbase64 = Base64.encodeToString(byteArray, Base64.NO_WRAP + Base64.URL_SAFE);
And add to JSONObject
JSONObject jo = new JSONObject();
try {
jo.put("id",users.get(counter).getId());
jo.put("firstname",users.get(counter).getFirstname());
jo.put("middlename",users.get(counter).getMiddlename());
jo.put("lastname",users.get(counter).getLastname());
jo.put("suffix",users.get(counter).getSuffix());
jo.put("image",imgbase64);
jo.put("date_registered",users.get(counter).getDate_registered());
} catch (JSONException e) {
e.printStackTrace();
}
And I will send it using retrofit
ServiceInterface si = RestClient.getClient();
Observable<Response> call = si.postUser(jo.toString());
Image size is 200kb and i got an error bad request
but when my image size is only 10kb it works fine.
please help.
Try to use Below solution for decode the image and send
Bitmap bitmap;
String encodedString ="";
String filepath=""; // your uploaded image file path
try {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 1;
bitmap = BitmapFactory.decodeFile(filepath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
} catch (Exception e) {
e.printStackTrace();
}
You can put encodedString to the your JSON.
Here is the PHP webservice for decode and upload image to server, also perform your operation to database.
<?php
include('../db/config.php');
// Get image string posted from Android App
$base=$_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];// this your image filename like testimage.jpg
//other files
$id= $_REQUEST['id'];
$firstname = $_REQUEST['firstname'];
$middlename = $_REQUEST['middlename'];// add your parameter
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/imgupload/uplodedimages' folder
$file = fopen('uploads/'.$filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
// echo 'Image upload complete, Please check your php file directory';
if(isset($filename) && $filename !=''){
$fileUrl = "http://yourdomain/android/upload/".$filename;
}else{
$fileUrl = '';
}
$sql=mysql_query("INSERT INTO tbl_name(Id,firstName,middleName,FileUrl) VALUES ('$Id','$firstName','$middleName','$fileUrl')");
?>
I suggest to try to use this solution, It will work.

how to upload an image to server in android

I am using params.put to post the strings to the server. But how do I post an image which is saved in the variable imgPreview.
comp_logo_id is the image field in Rest Api.
Here is My code:
params.put("title", title);
params.put("comp_logo_id", comp_logo_id);
params.put("company_name", company_name);
params.put("industry_selected", industry_selected);
You must convert image to base64 and upload to server .
In server convert base64 to image .
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;
}
String encodedImageData =getEncoded64ImageStringFromBitmap(your bitmap);
params.put("comp_logo_id", encodedImageData );

Decoded String Image Can't Be Display As BitMap in Android

Below is the portion of code I used to encode the image file from bitmap to base64 string by import android.util.Base64 in my android project:
`
Bitmap img_bmp=BitmapFactory.decodeStream(getContentResolver().
openInputStream(this.browseImageURI));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
img_bmp.compress(Bitmap.CompressFormat.JPEG, 30, baos);
byte[] image = baos.toByteArray();
String profile_img = Base64.encodeToString(image, Base64.DEFAULT);
`
The string profile_img will be saved in mysql database as a string.
When I retrieve the string value from database, I will decode image string from String to Bitmap by using the below code:
`
Intent i = getIntent(); //pass the value from previous activity
str_img= i.getStringExtra("img");
img_bm = StringToBitMap(str_img);
imgview = (ImageView)findViewById(R.id.imageView1);
imgview.setImageBitmap(img_bm); // display the image
//Function to convert string to bitmap
public Bitmap StringToBitMap(String image){
try{
byte [] encodeByte=Base64.decode(image,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
`
I expected it will display the image, however the image is not displayed and I get a log message from the Base64 decoder "--- decoder->decode returned false".
Can someone help me to figure out what is wrong in my code?
And do anyone know how to convert the base64 string image (pass from JSON to php script) into a blob format so that I can store it as BLOB in mysql.
Thank you in advance.

Categories

Resources