unable to post base64 converted image to rest service - android

I've written a code that selects image from gallery and convert it into a BASE64 string. as the selected images was too large the string is too big to be posted.
I have compressed the image so that the length of the string could be reduced. but still the length of the string is still large.
The code that i used is as follows,
This function sets the selected image in an imageView and
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
sPicturePath = cursor.getString(columnIndex);
cursor.close();
imageView = (ImageView) findViewById(R.id.imageView);
Bitmap bm = ShrinkBitmap(sPicturePath, 300, 300);
imageView.setImageBitmap(bm);
/**
* Compute size of the image selected image
*/
File file = new File(sPicturePath);
if (file.exists()) {
double bytes = file.length();
double kilobytes = (bytes / 1024);
double megabytes = (kilobytes / 1024);
System.out.println("megabytes : " + megabytes);
Log.d("size", String.valueOf(megabytes));
}
imageView.setImageBitmap(BitmapFactory.decodeFile(sPicturePath));
Bitmap bm1 = BitmapFactory.decodeFile(sPicturePath);
//CropImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm1.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArrayImage = baos.toByteArray();
encodedString = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
//Toast.makeText(getApplicationContext(), encodedString, Toast.LENGTH_SHORT).show();
String length = String.valueOf(encodedString.length());
//Toast.makeText(getApplicationContext(),lenght,Toast.LENGTH_SHORT).show();
Log.d("encodedString", encodedString);
Log.d("length", length);
ShrinkBitmap.java
Bitmap ShrinkBitmap(String file, int width, int height) {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
return bitmap;
}
What i want to achieve is to select an image from gallery convert it into a BASE64 string and post it through a REST service.

A GET request has URL length restrictions. You need to send the file using MultipartEntity using HttpURLConnection. You need to create a post request.
If your filename is image.jpg.
Bitmap bitmap = ...;
String filename = "image.jpg";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), filename);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("picture", contentPart);
String response = multipost("http://server.com", reqEntity);
And this is the multipost function.
private static String multipost(String urlString, MultipartEntity reqEntity) {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(conn.getOutputStream());
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return readStream(conn.getInputStream());
}
} catch (Exception e) {
Log.e(TAG, "multipart post error " + e + "(" + urlString + ")");
}
return null;
}
private static String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder.toString();
}
More info at this SO thread.

Related

How to resolve OutOfMemoryError on Bitmap in Android?

I want to set an image in ImageView, I am retrieving the image path in my first activity and I am passing it via Intent as a String to second activity. In the second activity I set the path to an ImageView. It's working properly, and I need to upload that picture to a server. So I decoded the path to a bitmap. It throws an OutOfMemoryError. How to resolve this issue?
And when I use front camera, there is no issues. Image is uploaded successfully. The problem is with the images taken by front camera of the device. What is the solution for this problem? Can anyone help?
Here is the code to convert the image path to a string and passing it via Intent:
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, MediaStore.Images.Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
try {
Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
intent.putExtra("ImagePath", photoPath);
MainActivity.this.startActivity(intent);
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, "Method invoked"+photoPath, Toast.LENGTH_SHORT).show();
}
}
Receiving Intent in Second Activity:
Intent camIntent = getIntent();
camPicPath = camIntent.getExtras().getString("ImagePath");
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(camPicPath));
Toast.makeText(getApplicationContext(), "PATHe"+camPicPath, Toast.LENGTH_SHORT).show();
bitmap = (BitmapFactory.decodeFile(camPicPath));
Method to Upload the file:
class ImageUploadTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://11.10.11.15/test/upload.php");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
/* entity.addPart("uploaded_file", new ByteArrayBody(data,
"myImage.jpg"));*/
// String newFilename= filename.concat("file");
// newFilename=filename+newFilename;
entity.addPart("uploaded_file", new ByteArrayBody(data,
filename));
// Log.e(TAG, "Method invoked");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String sResponse = builder.toString();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
Use the following method:
Bitmap bm = ShrinkBitmap(imagefile, 300, 300);
image.setImageBitmap(bm);
Bitmap ShrinkBitmap(String file, int width, int height) {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
return bitmap;
}
Or use inSampleSize when setting the image bitmap like this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
imageView.setImageBitmap(BitmapFactory.decodeFile(path, options));
you can add below property to application tag of manifiest file for high memory.
android:largeHeap="true"

Android - Resize & crop picture before sending without saving it

Please excuse my bad English, I'm French !
In my Android App, I have to resize and crop a picture from the gallery before sending it to a server WITHOUT saving it.
Here my code to send to the server :
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = imagePath;
String urlServer = "http://ip/serverApp/upload/transfert.php";
Log.e("UploadImage", urlServer);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try
{
File file = new File(imagePath);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
fileInputStream.close();
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
connection.setDoOutput(true);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
int bufferLength = 1024;
for (int i = 0; i < bytes.length; i += bufferLength) {
int progress = (int)((i / (float) bytes.length) * 100);
publishProgress(progress);
if (bytes.length - i >= bufferLength) {
outputStream.write(bytes, i, bufferLength);
} else {
outputStream.write(bytes, i, bytes.length - i);
}
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
outputStream.close();
outputStream.flush();
InputStream inputStream = connection.getInputStream();
// read the response
inputStream.close();
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.w("Upload image", "Response -> Code:"+serverResponseCode+" Message:"+serverResponseMessage);
return serverResponseCode;
}
catch (Exception ex)
{
ex.printStackTrace();
}
Now I need to code to resize and crop the picture in order to have image of a size of 350px/350px.
Do you know how I could do that ?
Thanks a lot.
OK !!!!
For the correct way follow this this code !
BUT : becarful, it's an example ! -> YOU SHOULDN'T DO A INTERNET REQUEST IN THE MAIN THREAD
for execute this code, the function exec(); should to be put into a "doInBackground()" of an asyncTask<Object, Object, Object>();
the startActivityForResult() and the override of onActivityResult() should to be into an activity class
tell me if it's correct !!!!
private int ACTIVITY_ID_PICK_PHOTO = 42;
private int maxWidth = 350;
private int maxHeight = 350;
private String url = "http://ip/serverApp/upload/transfert.php"
//Call the activity for select photo into the gallery
private void SelectPhoto(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, ACTIVITY_ID_PICK_PHOTO);
}
// check the return of the result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//check th id of the result
if (requestCode == ACTIVITY_ID_PICK_PHOTO)
selectPhotoControl(data);
}
//Working data
private void selectPhotoControl(Intent data) {
//check if any photo is selected
if (data == null)
return;
//get the uri of the picture selected
Uri photoUri = data.getData();
if (photoUri != null) {
//decode the Uri
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(photoUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//get the uri of the image
String filePath = cursor.getString(columnIndex);
cursor.close();
//get the image in the bitmap and resize the image
Bitmap bp = resize(filePath);
if (bp != null)
postImage(bp, filePath);
}
}
public static HttpResponse postImage(Bitmap bp, String uristr) throws ClientProtocolException, IOException {
//initialization of the postrequest
HttpPost httpPost = new HttpPost(url);
//create the multipart entitiy (if you want send another content)
MultipartEntity entity = new MultipartEntity(
//the boundary for separate the informations
HttpMultipartMode.BROWSER_COMPATIBLE, "------CustomBoundary", null);
if (bp != null) {
//create the bytes array for send the image
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//if you want to compress the image -> write the result into bos
bp.compress(CompressFormat.JPEG, 100, bos);
//get the filename of the image
String filename = uristr.substring(uristr.lastIndexOf("/") + 1,
uristr.length());
//put the picture into the body of this part
FormBodyPart fbp = new FormBodyPart("photo", new ByteArrayBody(
bos.toByteArray(), "image/jpeg", filename));
//add the part to the entity
entity.addPart(fbp);
}
//set the entity into the request
httpPost.setEntity(entity);
//execute the request
return exec(httpPost);
}
protected synchronized static HttpResponse exec(HttpRequestBase base) throws ClientProtocolException, IOException{
if (base != null)
//Execute the request
return mHttpClient.execute(base);
else
return null;
}
private Bitmap resize(String path){
// create the options
BitmapFactory.Options opts = new BitmapFactory.Options();
//just decode the file
opts.inJustDecodeBounds = true;
Bitmap bp = BitmapFactory.decodeFile(path, opts);
//get the original size
int orignalHeight = opts.outHeight;
int orignalWidth = opts.outWidth;
//initialization of the scale
int resizeScale = 1;
//get the good scale
if ( orignalWidth > maxWidth || orignalHeight > maxHeight ) {
final int heightRatio = Math.round((float) orignalHeight / (float) maxHeight);
final int widthRatio = Math.round((float) orignalWidth / (float) maxWidth);
resizeScale = heightRatio < widthRatio ? heightRatio : widthRatio;
}
//put the scale instruction (1 -> scale to (1/1); 8-> scale to 1/8)
opts.inSampleSize = resizeScale;
opts.inJustDecodeBounds = false;
//get the futur size of the bitmap
int bmSize = (orignalWidth / resizeScale) * (orignalHeight / resizeScale) * 4;
//check if it's possible to store into the vm java the picture
if ( Runtime.getRuntime().freeMemory() > bmSize ) {
//decode the file
bp = BitmapFactory.decodeFile(path, opts);
} else
return null;
return bp;
}
This answer [is based on another answer][1], 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.

android picture download

I return a Bitmap object according to a url, and the code for download picture:
URL url = new URL(imageUrlStr);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close
Then I save it to sdcard. It is ok to save picture.
Now the problem is it download the picture A when use this url to access. But it now shows another B picture in SDCARD. How to solve this problem?
You can identify images by hash-code. Not a perfect solution, good for the demo
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/** decodes image and scales it to reduce memory consumption*/
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
}
return null;
}
Use you just need to use method "getBitmap(String)" with your desired url as String

How can I resize the image that was retrieved via URL and save it?

I am getting an image via URL from the Internet and trying to resize (to a smaller size) before saving it. I managed to save it, but I'm unable to resize it. How could I do that? Here is the code:
URL url = new URL(LogoURL);
InputStream input = url.openStream();
try {
OutputStream output = new FileOutputStream("data/data/com.android.mylogo/logo.jpg");
try {
//byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
System.out.println("Buffer Length is \t:-" + buffer.length);
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
System.out.println("inside while");
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
System.out.println("saved image");
}
} finally {
input.close();
}
If you want to downscale the image to particular dimensions, you can use the following code:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(LogoURL);
try {
HttpResponse response = client.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(LOG_TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = null;
BufferedInputStream bis = null;
try {
is = url.openStream();
bis = new BufferedInputStream(is);
int sampleSize = 1;
bis.mark(Integer.MAX_VALUE);
Options bounds = new Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeStream(bis, null, bounds);
if (bounds.outWidth != -1) {
int width = bounds.outWidth;
int height = bounds.outHeight;
boolean withinBounds = width <= YOUR_DESIRED_WIDTH && height <= YOUR_DESIRED_HEIGHT;
int newWidth = width;
int newHeight = height;
while (!withinBounds) {
newWidth /= 2;
newHeight /= 2;
sampleSize *= 2;
withinBounds = newWidth <= YOUR_DESIRED_WIDTH && newHeight <= YOUR_DESIRED_HEIGHT;
}
} else {
Log.w(LOG_TAG, "Can't open bitmap at " + url);
return null;
}
try {
bis.reset();
} catch (IOException e) {
if(is != null){
is.close();
}
if(bis != null){
bis.close();
}
if(!entity.isRepeatable()){
entity.consumeContent();
response = client.execute(request);
entity = response.getEntity();
}
is = entity.getContent();
bis = new BufferedInputStream(is);
}
Options opts = new Options();
opts.inSampleSize = sampleSize;
Bitmap bm = BitmapFactory.decodeStream(bis, null, opts);
return bm;
} finally {
if (is != null) {
is.close();
}
if (bis != null) {
bis.close();
}
entity.consumeContent();
}
}
} catch (IOException e) {
request.abort();
Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
} catch (IllegalStateException e) {
request.abort();
Log.w(LOG_TAG, "Incorrect URL: " + url);
} catch (Exception e) {
request.abort();
Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
}
When you open the image with Options bounds = new Options(); bounds.inJustDecodeBounds = true;, then the image data won't be downloaded, only the size of the image. I use this size to calculate the new scale ratio to get the desired width and height.
With the option Options opts = new Options(); opts.inSampleSize = sampleSize; the BitmapFactory will download an already resized image. You save memory, and bandwidth this way.
Note, that the sampleSize values should be powers of 2. It works with different numbers as well, but this is much more efficient.
JPGs are compressed anyway, so there's no need to try to compress them any further.
In general, to compress something, have a look at the classes of java.util.zip package.

How to handle out of memory error?

I am using following code to display bitmap in my ImageView.
When I try to load image of size for example bigger than 1.5MB it give me error.
Any one suggest me solution?
try {
URL aURL = new URL(myRemoteImages[val]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = null;
try
{
is= conn.getInputStream();
}catch(IOException e)
{
return 0;
}
int a= conn.getConnectTimeout();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm;
try
{
bm = BitmapFactory.decodeStream(bis);
}catch(Exception ex)
{
bis.close();
is.close();
return 0;
}
bis.close();
is.close();
img.setImageBitmap(bm);
} catch (IOException e) {
return 0;
}
return 1;
Log cat:
06-14 12:03:11.701: ERROR/AndroidRuntime(443): Uncaught handler: thread main exiting due to uncaught exception
06-14 12:03:11.861: ERROR/AndroidRuntime(443): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
06-14 12:03:11.861: ERROR/AndroidRuntime(443): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
You should decode with inSampleSize option to reduce memory consumption. Strange out of memory issue while loading an image to a Bitmap object
Another option inJustDecodeBounds can help you to find correct inSampleSize value http://groups.google.com/group/android-developers/browse_thread/thread/bd858a63563a6d4a
In general I think this blog covers the best practices on how to watch memory allocation/ how to use Weak/Soft References to avoid overflows.
Hope this helps.
try {
Bitmap bitmap=null;
byte[] profileImageInBytes;
String url="http://photo.net/learn/collage/complete-full-size.jpg";
HttpGet httpRequest = null;
httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
System.gc();
Runtime.getRuntime().gc();
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
bmpFactoryOptions.inTempStorage = new byte[32 * 1024];
bmpFactoryOptions.inSampleSize = 4;
bmpFactoryOptions.outWidth = 640;
bmpFactoryOptions.outHeight = 480;
bmpFactoryOptions.inDither=false;
bmpFactoryOptions.inInputShareable=true;
bitmap = BitmapFactory.decodeStream(instream, new Rect(), bmpFactoryOptions);
System.out.println("hi " +bitmap);
Bitmap map = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
System.out.println("23");
System.out.println("hihi hi " +map);
BitmapDrawable bmd = new BitmapDrawable(map);
System.out.println("24");
System.out.println("hihi hi " +bmd);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
System.out.println(stream);
map.compress(Bitmap.CompressFormat.JPEG, 100, stream);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) 400);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) 400);
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
Bundle params=new Bundle();
params.putString("method", "photos.upload");
profileImageInBytes = stream.toByteArray();
System.out.println(profileImageInBytes);
System.out.println(" profile image bytes ");
System.out.println("Bytes : " + profileImageInBytes);
params.putByteArray("picture", profileImageInBytes);
System.out.println("My Picture : " + params);
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
System.out.println("Uploading");
}
catch (IOException e) {
e.printStackTrace();
}

Categories

Resources