1

I have a picture from camera as bitmap. This picture I want to send as jpeg to the server via http Post, something like this:

Bitmap photo;
StringEntity reqEntity = new StringEntity(photo);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(request);

I have this code from azure

//Request headers. 
request.setHeader("Content-Type", "application/json"); request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey); 
// Request body. 
StringEntity reqEntity = new StringEntity("{\"url\":\"upload.wikimedia.org/wikipedia/comm‌​ons/c/c3/…\"}"); 
request.setEntity(reqEntity);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
tobias
  • 2,322
  • 3
  • 33
  • 53

2 Answers2

1

Convert your bitmap to base64 string, try below code and post that string to server

public static String encodeTobase64(Bitmap image)
{
   Bitmap immagex=image;
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   immagex.compress(Bitmap.CompressFormat.PNG, 100, baos);
   byte[] b = baos.toByteArray();
   String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
   return imageEncoded;
}

public static Bitmap decodeBase64(String input)
{
   byte[] decodedByte = Base64.decode(input, 0);
   return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
Sunil P
  • 3,698
  • 3
  • 13
  • 20
1

First of all convert bitmap to jpeg. For converting bitmap to jpeg, you can refer to : - How to convert a bitmap to a jpeg file in Android?

After that use multipart entity to send files to server.

To send files to server: -

InputStream is = null;
String response ="";
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("profile_pic", new FileBody(new File(profileImagePath)));

try {

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    httpPost.setEntity(mpEntity);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    response = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}
Prashant Kumar Sharma
  • 1,120
  • 1
  • 11
  • 21