Java – Android, compressing images

Android, compressing images… here is a solution to the problem.

Android, compressing images

I’m sending an image over the network via wifi or mobile network to store in the server and retrieve it again. I’ve done this, but it’s slowing down my app due to the size of the image taken by the camera, just pointing out that I’m opening the gallery and taking a photo from there instead of taking a photo directly from the app. I noticed that whatsapp images taken from the camera and gallery have been compressed to approximately. 100kb。

Currently my code takes a file and converts it to bytes, then sends it. This is how to get a file and convert it to bytes.

private void toBytes(String filePath){
        File file = new File(filePath);
        InputStream is = new BufferedInputStream(new FileInputStream(file));  
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        bytes = new byte[(int) filePath.length()];
        int bytes_read;
        while((bytes_read =, 0, bytes.length)) != -1){
            buffer.write(bytes, 0, bytes_read);
        bytes = buffer.toByteArray();
    }catch(Exception err){
        Toast.makeText(getApplicationContext(), err.toString(), Toast.LENGTH_SHORT).show();

So my question is how to compress an image before sending? Also, I don’t need the image to retain a high pixel count because when the app uses the image, it will only take up half of the device’s screen.

Thank you for any help.


Bitmap class has a compress method.
But you may need to scale the image createScaledBitmap, which is also available in the same class.

Related Problems and Solutions