How to send and receive bitmap on restful server

Asked

Viewed 182 times

6

Staff did a search and found very little content, I would like some tips because I never did it. How do I send and receive a bitmap to a server? Send with Json? Convert to Base64? What is the best way to send and how should my method be on the server to receive? Thanks

  • 2

    See if it helps you http://answall.com/questions/16374/android-enviar-e-receber-imagem-via-webservice

  • It seems to help a lot, I will implement what he did and see if it works. Vle

  • 1

    I disagree to close as duplicate because the answers to this question are much better than the other.

  • So far there were no answers to the question, I agree with you @Victorstafusa

2 answers

5


Simply upload as binary content.

String url = "http://seusite.com.br";
File file = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath(),"suaImagem.jpg");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // mande em pacotes separados se necessario
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);

} catch (Exception e) {
    // Trate seu erro
}

Adapted example of this answer.

4

Correct is to encode the image in Base64 and send it through the server, before sending, convert the image with Base64 to a Byte array and send this whole Object.

//Codificar uma imagem
Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(),
                    R.drawable.imagem);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bitMapData = stream.toByteArray();
String encodedImage2 =Base64.encodeToString(bitMapData,Base64.DEFAULT);

//Decodificar
byte[] arquivo = null;
arquivo = Base64.decode(objeto.imagem.toString());
  • Opa blz, I saw that gains much more performance with Base64. You know how I will receive on the server? Thanks for the help

  • 2

    @What actually loses performance; binary content encoded in Base64 gets around 37% higher.

  • Ideally I would pass a direct string then.

  • @Roque There is no need to perform any transformation on the original content; it can be sent as an array of bytes even.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.