Dynamically conversion of image to binary and vice versa - android

How can I convert image to binary data..???
I want to send that converted binary data to
another device or to the web server.
Which mechanism is best to do this.?

Image is in Bitmap then use the following code to convert that image to binary. By using following code
Bitmap photo;// this is your image.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
To get Image From Binary use the following sample:
Bitmap bMap = null;
bMap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);

I found a good example for uploading the image to the server.
create a bitmap variable before do anything.
variable to set a name to the image into SD card.
this variable, you have to put the path for the File, It's up to you.
sendData is the function name, to call it, you can use something like
sendData(null).
remember to wrap it into a try catch.
private Bitmap bitmap;
public static String exsistingFileName = "";
public void sendData(String[] args) throws Exception {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// here, change it to your php;
HttpPost httpPost = new HttpPost("http://www.myURL.com/myPHP.php");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
bitmap = BitmapFactory.decodeFile(exsistingFileName);
// you can change the format of you image compressed for what do you want;
// now it is set up to 640 x 480;
Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CompressFormat set up to JPG, you can change to PNG or whatever you want;
bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
// sending a String param;
entity.addPart("myParam", new StringBody("my value"));
// sending a Image;
// note here, that you can send more than one image, just add another param, same rule to the String;
entity.addPart("myImage", new ByteArrayBody(data, "temp.jpg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
} catch (Exception e) {
Log.v("myApp", "Some error came up");
}
}

Try this
Let img contains Bitmap image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
imageInByte now contains bytedata of bitmap image.
For converting reverse
Bitmap bp = BitmapFactory.decodeByteArray(imgArray, 0,imgArray.length);
Hope this may help you

if you want to send to webserver use HttpPost request using HttpClient

Related

android send binary data in http

I have the following code to send an image (bitmap binary data) using android http default client:
//gets raw binary data and convert it to a string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageData = new String(imageBytes);
//http put body
StringEntity se = new StringEntity(imageData);
putRequest.setEntity(se);
I need to send its raw binary content in the put request body, but it seems that the content is not being properly sent.
I can send an image binary using curl with the --data-binary (that's what I am trying to do in android).
Is the process in converting the bitmap binary to string correct?
Thanks!
Well, my bad.
In case anyone makes the same mistake:
I should have used the ByteArrayEntity class instead of the StringEntity one:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
//http put body
ByteArrayEntity be = new ByteArrayEntity(imageBytes);
putRequest.setEntity(be);
I was trying to convert the bytearray into a string and send it, the correct way to do it is to use the ByteArrayEntity class.

how to upload image as byte array to Rest web-service using http post method in android

I created app which can upload the images to the web-service. In that, how can I upload use the image as byte[] array while uploading image using HTTP post method to rest web-service.
How to pass the byte[] array to web-service along with file name and file length?
Drawable d = context.getResources().getDrawable(R.drawable.human_head);
Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
byte[] bitmapdata = stream.toByteArray();
entity.addPart("image", new ByteArrayBody(bitmapdata,".png"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, WebService.getInstance(Constants.WEB_SERVER).getLocalContext());

How to convert a picture before sending to the server?

in my current app I am sending pictures to my server. Now I have the problem that these pictures are sometimes too big. What is the best approach to downsize a picture before sending it to the server. Currently I stored the URI of the picture in a database (/mnt/sdcard/DCIM/SF.png) and send it to the server. I want to shrink the resolution of the image so that it will need a smaller amount of diskpace. Is there a way to convert images in android?
Can someone help me how to solve this in a good way?
Thanks
i used the following code to send the image to server, here i convert the image to byte array. Here first you need to decode the image from URI then convert the bitmap to byte array.
To decode bitmap from URI:
Bitmap imageToSend= decodeBitmap("Your URI");
Method to decode the URI
Bitmap getPreview(URI uri) {
File image = new File(uri);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
Code to send the image to server
try {
ByteArrayOutputStream bosRight = new ByteArrayOutputStream();
imageToSend.compress(CompressFormat.JPEG, 100, bosRight);
byte[] dataRight = bosRight.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("url to send");
ByteArrayBody babRight = new ByteArrayBody(dataRight,
"ImageName.jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("params", babRight);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
Log.v("Response value is", sResponse);
JSONObject postObj = new JSONObject(sResponse);
String successTag = postObj.getString("success");
if (successTag.equals("1")) {
imageDeletion();
} else {
}
}
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
for sending the image to a server you can encode it in Base64 and then send the Base64 encoded string to the server...
the base64 class in android doesn't support encoding so you will have to download the Bae64 java class file... You get it here http://iharder.sourceforge.net/current/java/base64/
after that its very simple.For example
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.YOURIMAGE);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String encodedstring=Base64.encodeBytes(ba);
Then send the encoded string as a normal name value pair
and a good example is given in this link http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/

Algorithm to reduce byte array image size to 1MB android

I want to write a Algorithm to reduce image size to around 1MB before posting data to database in android.
My image is in byte array and i have to send byte array to database.
Here is the code i am trying, but sometimes it gives out of memory exception at bm.compress(CompressFormat.JPEG, 100, bos); line.
Code:
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (imgData != null) {
if (imgData.length > 1048576) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bm = BitmapFactory.decodeByteArray(imgData, 0, imgData.length,options);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, bos);
bm.recycle();
bm = null;
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
reqEntity.addPart("image_data", bab);
} else {
ByteArrayBody bab = new ByteArrayBody(imgData, "image.jpg");
reqEntity.addPart("image_data", bab);
}
Moreover i dont want to use Bitmap.compress as i am already using BitmapFactory options.
Thanks for help in advance!

Android Image resize (resample/downsample) before uploading

private void doFileUpload(){
File file1 = new File(selectedPath1);
String urlString = "http://example.com/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
I get this code from internet. it's work but when I try upload bigger file than 1Mbyte,
I face an error with filesize.
I know how to resize bitmap images and but I have no idea upload the resized bitmap image.
how can I resize and upload with filebody?
Thanks in advance
You need to not only resize the Bitmap, but you also need to encode the result as a .jpg image. Therefore, you must open the file and convert it to a Bitmap, resize the Bitmap to a smaller image, encode the image into a byte[] array, and then upload the byte[] array in the same manner as you have uploaded your file file1.
If the Bitmap is large, which it clearly is, you won't have enough heap memory to open the entire thing, so you will have to open it with BitmapFactory.Options.inSampleSize.
First, open the reduced size Bitmap:
Uri uri = getImageUri(selectedPath1);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // Example, there are also ways to calculate an optimal value.
InputStream in = in = contentResolver.openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
Next, encode into a byte[] array:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] bitmapdata = bos.toByteArray();
Finally, use reqEntity.addPart() to add the byte[] array directly, or write to a smaller file and add the file as in your current example.
This answer is based on another answer, but I had some problems with that code, so I post the edited and working code.
I did it like this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.outWidth = 50; //pixels
options.outHeight = 50; //pixels
InputStream in = context.getContentResolver().openInputStream(data.getData()); // here, you need to get your context.
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bitmapdata = baos.toByteArray();
Notice that, data is the returned data from the Intent you use to get the file. If you already have the file path, just use that...
And now, when you are creating the HTTP Entity, add:
FormBodyPart fbp = new FormBodyPart("image", new ByteArrayBody(baos.toByteArray(), "image/jpeg", "image"));
entity.addPart(fbp);
Also, notice that you need a MultipartEntity to upload files.

Categories

Resources