How to convert a picture before sending to the server? - android

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/

Related

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.

Dynamically conversion of image to binary and vice versa

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

Android - skia decode error for images

I have been trying to decode an image as follows:
String dat = jobJect.getString("dat");
client = new DefaultHttpClient();
String url2 = url1 + dat;
request = new HttpGet(url2);
request.setHeader("Cookie", "hcsid=" + GlobalConfig.hcSid);
response = client.execute(request);
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(
response.getEntity());
InputStream im = bufHttpEntity.getContent();
OutputStream out = null;
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
CameraActivity.copy(im, out);
out.flush();
final byte[] data = dataStream.toByteArray();
mBitMap = BitmapFactory.decodeByteArray(data, 0, data.length);
Although I get an image, it doesn't get decoded and throws this error:
09-29 11:27:38.675: DEBUG/skia(14907): --- decoder->decode returned false
I'm following this code which handles a skia error:
http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/util/ImageUtilities.java
But it doesn't solve the issue.
Can anyone please help?
Check this bug report:
http://code.google.com/p/android/issues/detail?id=9064

Android : Getting this error while downloading image from remote server: SkImageDecoder::Factory returned null

I am trying to download images from a remote server, the number of images downloaded is 30. The code i am using to download image is as below. Some images download successfully and some images don't download and raises the above exception. What might be the problem.
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), 4*1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 4 * 1024);
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e("","Could not load Bitmap from: " + url);
} finally {
try{
in.close();
out.close();
}catch( IOException e )
{
System.out.println(e);
}
}
return bitmap;
}
Please look on my this post
Image download code works for all image format, issues with PNG format rendering
In my case I solved this error with encode the url
Because image url that i wanted to download has the Persian letters(or other Unicode character) in it
So I replaced all Persian characters with encoded UTF-8 letters

Categories

Resources