Android How to - Compress Bitmap








Question

We would like to know how to compress Bitmap.

Answer

The following code shows how to compress a Bitmap with Bitmap.CompressFormat.JPEG.

It creates a ByteArrayOutputStream first and writes the compressed bytes into ByteArrayOutputStream.

BitmapFactory is used to create a Bitmap from the byte array stream.

//w  ww  .ja va  2s  . co m
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {
  public static Bitmap compressImage(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 70, baos);
    int options = 100;
    while (baos.toByteArray().length / 1024 > 100) {
      baos.reset();
      image.compress(Bitmap.CompressFormat.JPEG, options, baos);
      options -= 10;
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
    return bitmap;
  }

}