Android Crop Center of Bitmap

Viewed 116003

I have bitmaps which are squares or rectangles. I take the shortest side and do something like this:

int value = 0;
if (bitmap.getHeight() <= bitmap.getWidth()) {
    value = bitmap.getHeight();
} else {
    value = bitmap.getWidth();
}

Bitmap finalBitmap = null;
finalBitmap = Bitmap.createBitmap(bitmap, 0, 0, value, value);

Then I scale it to a 144 x 144 Bitmap using this:

Bitmap lastBitmap = null;
lastBitmap = Bitmap.createScaledBitmap(finalBitmap, 144, 144, true);

Problem is that it crops the top left corner of the original bitmap, Anyone has the code to crop the center of the bitmap?

10 Answers

You can used following code that can solve your problem.

Matrix matrix = new Matrix();
matrix.postScale(0.5f, 0.5f);
Bitmap croppedBitmap = Bitmap.createBitmap(bitmapOriginal, 100, 100,100, 100, matrix, true);

Above method do postScalling of image before cropping, so you can get best result with cropped image without getting OOM error.

For more detail you can refer this blog

    val sourceWidth = source.width
    val sourceHeight = source.height
    val xScale = newWidth.toFloat() / sourceWidth
    val yScale = newHeight.toFloat() / sourceHeight
    val scale = xScale.coerceAtLeast(yScale)

    val scaledWidth = scale * sourceWidth
    val scaledHeight = scale * sourceHeight
    val left = (newWidth - scaledWidth) / 2
    val top = (newHeight - scaledHeight) / 2
    val targetRect = RectF(
        left, top, left + scaledWidth, top
                + scaledHeight
    )
    val dest = Bitmap.createBitmap(
        newWidth, newHeight,
        source.config
    )
    val mutableDest = dest.copy(source.config, true)
    val canvas = Canvas(mutableDest)
    canvas.drawBitmap(source, null, targetRect, null)
    binding.imgView.setImageBitmap(mutableDest)
Related