Android How to - Crop Bitmap Center








Question

We would like to know how to crop Bitmap Center.

Answer

The following method shows how to crop a Bitmap. The operation is done via a Canvas object.

//from  w  w w .  j  a  va  2 s.  c  o m
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

public class Main {

    public static Bitmap cropCenter(Bitmap bitmap) {

        int minSize = Math.min(bitmap.getWidth(), bitmap.getHeight());
        int diffSize = Math.abs(bitmap.getWidth() - bitmap.getHeight());

        Bitmap targetBitmap;
        targetBitmap = Bitmap.createBitmap(minSize, minSize, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(targetBitmap);
        Matrix matrix = new Matrix();
        if (bitmap.getWidth() >= bitmap.getHeight())
            matrix.setTranslate(diffSize, 0);
        else
            matrix.setTranslate(0, diffSize);

        canvas.drawBitmap(targetBitmap, new Matrix(), new Paint());

        bitmap.recycle();
        return targetBitmap;
    }
}