Search code examples
androidcompressionpngandroid-cameraandroid-bitmap

Compress bitmap or byte[] after taking picture


I am trying to reduce the size of the bitmap after taking the picture. I am able to reduce the size to max 900kb but I wan to reduce it further as much as possible

First I do this:

public static Bitmap decodeSampledBitmapFromResource(byte[] data,
                                                     int reqWidth, int reqHeight) {
 //reqWidth is 320
//reqHeight is 480
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, 0, data.length, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeByteArray(data, 0, data.length, options);
}

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

then this

bitmap.compress(Bitmap.CompressFormat.PNG, 10, fos);

How do i compress the bitmap further ? or Should I compress the byte[] instead? I just want to send documents, black and white.


Solution

  • You should use jpg instead of png if the alpha channel is not needed. Also you can change the color config of your output bitmap:

    // Decode bitmap with inSampleSize set
    options.inPreferredConfig= Bitmap.Config.RGB_565;
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeByteArray(data, 0, data.length, options);