upload image to server without compress image - android

I want to upload image to server without compress it because I am compressing the image in another function and than sending the image to uploadtoserver function.
here is my code to upload the image to server but i dont understand how to upload the image to server without compress it.
public String uploadtoserver(String imgPathm){
//int flag=0;
try{
Bitmap bm = BitmapFactory.decodeFile(imgPathm);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeToString(ba, 0);
//ba1 = Base64.encodeBytes(ba);
return ba1;
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
}
I just want to know will my above code work to upload image to server. thank you

Related

image upload using parse API

I am having trouble trying to upload the image on server using Parse API. I can read from the server and update data on any column except uploading image.
I have picked the image from the device and displayed in imageView..
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
// Set the Image in ImageView after decoding the String
imageView.setImageURI(selectedImage);
Picasso.with(this).load(selectedImage).fit().centerCrop().into(imageView);
//resizing the image part 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//to Compress the image
//Quality Accepts 0 - 100
//0 = MAX Compression (Least Quality which is suitable for Small images)
//100 = Least Compression (MAX Quality which is suitable for Big images)
bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
//uploading the image to server
byte[] imageInByte = imgDecodableString.getBytes();
final ParseFile bitmapFile = new ParseFile(imageInByte);
bitmapFile.saveInBackground();
//current user is already logged in.
ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
userDisplayImage.put("photo", bitmapFile);
userDisplayImage.saveInBackground();
In your code :
final ParseFile bitmapFile = new ParseFile(imageInByte);
bitmapFile.saveInBackground();
the bitmapFile is uploaded in a background thread, hence by the time you reach to the next statement :
ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
userDisplayImage.put("photo", bitmapFile);
userDisplayImage.saveInBackground (...);
The bitmapFile is not completely uploaded and hence it userDisaplyImage is not able to make a pointer towards it.
You can try the following to fix it :
final ParseFile bitmapFile = new ParseFile(imageInByte);
bitmapFile.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null){
Log.i("hello"," photo saved ");
ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
userDisplayImage.put("photo", bitmapFile);
userDisplayImage.saveInBackground ();
} else {
e.printStackTrace();
Log.i("Error", e + "photo not saved");
}
}
});

Uploading Image from Android to Node

I am trying to upload multiple images to my node server via Android Studio. However the image file always seems to be corrupt on the server. I am able to take and preview the picture in Android but not able to store it on my server.
Here is my server code
app.post('/upload', function(req, res) {
var base64Data = req.rawBody;
fs.writeFile("test.jpg",base64Data,'base64',function(err,written){
if(err) console.log(err);
else {
console.log("file Succesfully written ");
cloudinary.uploader.upload("test.jpg", function (image) {
if(image !== undefined) {
res.json({link: image.secure_url}).end();
console.log("url = " , image.secure_url);
// fs.unlink(ImageFile);
} else console.log.error("Error uploading to Cloudinary, ", image);
});
}
});
});
Here is my front end code I use to convert my bitmap to an encoded Base64 String.
final String encodedString = ImageBase64.encode(fileArray.get(i));
Here is a log of what encodedString holds after being set. Obviously the full value is not displayed.
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAMgA+gDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
However on my backend it is displayed as this
2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2F2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2FwAARCAMgA%2BgDASIA%0AAhEBAxEB%2F8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ
If you get it url encoded then you should url decode it.
InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(uri);//uri is the image URI
Bitmap bm = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArray = baos.toByteArray();
String encodedImage = Base64.encodeToString(byteArray,Base64.NO_WRAP);//encodedImage is your image string
} catch (FileNotFoundException e) {
e.printStackTrace();
}

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.

Image not decoding

I am getting this image as a byte array. So I encode the bytearray and store it in db. Later decode this byte array and saved it in sd card. Issue is that, I am not able to load this image into image view. It tells, skia--> decoder decode false. The bytearray could not be converted to bitmap. Here is the code I used to convert the bytearray to bitmap
Infact, not even able to open the image in Imagebrowser in android device (I have tried in Es Image browser also). But, this image if I open with chrome browser or HTML viewer, it opens flawlessly.
byte[] byteArray= android.util.Base64.decode(in.getBytes(), android.util.Base64.DEFAULT);
if (byteArray != null) {
Log.d(Utilities.class.getSimpleName(), byteArray.toString() + "byteArray Length-->" + byteArray.length);
} else {
Log.d(Utilities.class.getSimpleName(), "byteArray is null");
}
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Encoding code :
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = conn.getInputStream();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}
response.append(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT));
Here is the base64 string which I get
Base64 string of image
Can anyone help me is sorting out this issue.

Encode facebook url image to BASE 64 string in android

Let me explain my problem.
I am trying to set Facebook profile image in app Imageview some thing like this ..
// Getting Facebook URL image and converting same to bitmap
Bitmap mIcon1;
URL img_value = new URL("http://graph.facebook.com/"+ userProfileID +"/picture?type=square");
BitmapFactory.Options options = new BitmapFactory.Options();
mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream(), null, options);
Then after ..
// I am setting bitmap to imageview .. some thing like ..
if(mIcon1!=null) {
user_picture.setImageBitmap(mIcon1);
}
Up to here it is working great ...
Now I need to save that Facebook Profile image into my DB located at server ...
I am performing that stuff some thing like ..
// Created a method for encoding ..
public static String encodeTobase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
// Now trying to use this method to get encoded BASE 64 image in string ..
String final_image = encodeTobase64(mIcon1);
Now when I try to send this string to my server then at server end I am recieving broken link ... Instead I must say that it's not working ..
I need to perform two of stuff
Encode Facebook profile image to Encoded BASE 64 string so as to send same to server.
Get type of image (i.e. PNG/ JPG ... ) or compress and send that image in one specific format.
Looking forward for any suggestion on this.
Thanks!
I got solution of this and hope this will help some one ..
# Base concept :-- We generally use GET or POST method while sending data to server.
1- GET:-- In this method you can only send specific amount of data ..
2- POST :-- In this method you can send huge amount of data ..
Problem was :-- Exact problem was that .. I was using GET method while sending data to server. Above mentioned concept was know to me . but, some how I did that mistake.
Solution :-- You simply need to send data to server using POST method instead of GET.
Complete solution for this in undermentioned :--
// Define your ASYNC TASK like ..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new ImageTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else{
new ImageTask().execute();
}
AND
// Now here comes your complete Async Task over here ..
private class ImageTask extends AsyncTask<Void, Integer, Void> {
Bitmap mIcon1;
#Override
protected Void doInBackground(Void... params) {
URL img_value = null;
Log.d("taking", "2");
try {
if(type_of_login.equalsIgnoreCase("facebook")){
img_value = new URL("http://graph.facebook.com/"+ user_id +"/picture?type=square");
System.out.println("Complete URl is:============================= " + img_value);
}else{
img_value = new URL("https://plus.google.com/s2/photos/profile/"+ user_id +"?sz=50");
System.out.println("Complete URl is:============================= " + img_value);
}
//img_value = new URL("http://graph.facebook.com/"+ userProfileID +"/picture?type=square");
BitmapFactory.Options options = new BitmapFactory.Options();
mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream(), null, options);
Log.d("taking", "3" + img_value);
Log.d("taking", "3" + mIcon1);
Log.d("taking", String.valueOf(mIcon1));
ByteArrayOutputStream bao = new ByteArrayOutputStream();
mIcon1.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
encoded_image =Base64.encodeToString(ba,Base64.DEFAULT);
System.out.println("Encoded image is : ===== " + encoded_image);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if(mIcon1!=null)
{
user_pic.setImageBitmap(mIcon1);
get_string_image = encodeTobase64(mIcon1);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
}
}
}
Now finally our dream method ..
public static String encodeTobase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
Now when you need to send data over API then simply execute HttpPost instead of HttpGet
That's it .. you are good to go with this ..

Categories

Resources