Compress camera image before upload

Take a look over here: ByteArrayOutputStream to a FileBody

Something along these lines should work:

replace

File file = new File(miFoto);
ContentBody foto = new FileBody(file, "image/jpeg");

with

Bitmap bmp = BitmapFactory.decodeFile(miFoto)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename");

If file size is still an issue you may want to scale the picture in addition to compressing it.


Convert image to Google WebP format it will save you lots of bytes see the following two articles you can also convert webP into JPG/PNG/GIF whatever you want on server side.

Java Wrapper of Google WebP API

How to check out Google WebP library and use it in Android as native library

First, you need to get pixels from Bitmap.

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

int bytes = bitmap.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buffer);
byte[] pixels = buffer.array();

Then, you can get WebP byte array.

int stride = bytes / height;
int quality = 100;
byte[] encoded = libwebp.WebPEncodeRGBA(pixels, width, height, stride, quality);

Test.png (Size: 106KB) Test.png (Size: 106KB) Test.webp(Size: 48KB) Test.webp(Size: 48KB)


Using okhttp I upload like this:

MediaType MEDIA_TYPE_PNG
                        = MediaType.parse("image/jpeg");

                //Compress Image
                Bitmap bmp = BitmapFactory.decodeFile(fileToUpload.getAbsolutePath());
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 70, bos);

                RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addFormDataPart("photo", fileToUpload.getName(), RequestBody.create(MEDIA_TYPE_PNG, bos.toByteArray()))
                        .build();

                request = new Request.Builder()
                        .url(urlToUploadTo)
                        .post(requestBody)
                        .build();

                try {
                    response = client.newCall(request).execute();
                    if (response != null) {
                        if (response.isSuccessful()) {
                            responseResult = response.body().string();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }