CVD
CVD

Reputation: 27

Image upload from android app

In my application I'm uploading an image on to the server. Here in the below code I'm uploading an image from the drawable folder. But how can I upload an image from an imageview from the layout xml? similarly like findviewbyid.imgid

My layout name is main.xml and image id is imgid

kindly help me...

 Bitmap bitmap =
 BitmapFactory.decodeResource(getResources(),R.drawable.avatar);       
 ByteArrayOutputStream stream = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
 byte [] byte_arr = stream.toByteArray();
 String image_str = Base64.encodeBytes(byte_arr);
 ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

 nameValuePairs.add(new BasicNameValuePair("image",image_str));

Upvotes: 1

Views: 2223

Answers (1)

Krutik
Krutik

Reputation: 732

We can upload image using Base64 string and multipart entity

for base64 string

ByteArrayOutputStream baos = new ByteArrayOutputStream();
        btMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the
        byte[] b = baos.toByteArray();
        base64String = Base64.encodeBytes(b);

and for multipart

HttpPost httppost = new HttpPost("http://localhost:8080/upload.php");
File file = new File(yourimagepath);

MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

Upvotes: 2

Related Questions