Reduce size of Bitmap in Android

I am describing how to reduce image size by compressing and reducing the quality of the image. This can be useful when you want to upload or save compressed image sizes in server. This particular code converts the Image URI to WEBP compressed bitmap.  

private Bitmap compessBitmap(Context context, Uri uri, int IMAGE_SIZE) throws IOException {
    int quality = 100;
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);

    int byteArrayLength = Integer.MAX_VALUE;
    ByteArrayOutputStream bos = null;

    while((byteArrayLength/1000)>= IMAGE_SIZE){
        bos = new ByteArrayOutputStream();


        byteArrayLength = bos.toByteArray().length;

        Log.w("TAG","Image Size is now: "  + byteArrayLength+"");
    try {
        byte[]bosBytes = bos.toByteArray();
        return BitmapFactory.decodeByteArray(bosBytes, 0, bosBytes.length);
    }catch (NullPointerException e){
        return bitmap;


BitmapFormat specifies the image format that the image can be compressed into. There are three formats that Android SDK supports and they are PNG, JPG and WEBP. 

There are instances where we take image from camera or gallery and process the data. When we take image from camera we get Uri in onActivityResult. To turn Uri into bitmap we use a single line function to convert.

Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);

The function reduces the size as long as the compressed size reaches IMAGE_SIZE passed as one of the parameter,
If you want to reduce the size of the image to 100kb then pass 100 in IMAGE_SIZE

Leave a Reply