Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop image to square - Android

Tags:

How can I cut rectangular image (600 x 300) from left and right to fit in square ImageView ? I don't want to resize image, I just want to crop it, to be 300 x 300.

[SOLUTION]

As @blackbelt said

Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);

is great for cropping images. So how can you automatically crop images with different sizes. I create this simple code for that:

// From drawable
Bitmap src= BitmapFactory.decodeResource(context.getResources(), R.drawable.image);

// From URL
Bitmap src = null;
try {
    String URL = "http://www.example.com/image.jpg";
    InputStream in = new java.net.URL(URL).openStream();
    src = BitmapFactory.decodeStream(in);
} catch (Exception e) {
    e.printStackTrace();
}

int width = src.getWidth();
int height = src.getHeight();
int crop = (width - height) / 2;
Bitmap cropImg = Bitmap.createBitmap(src, crop, 0, height, height);

ImageView.setImageBitmap(cropImg);
like image 536
KiKo Avatar asked Oct 08 '14 18:10

KiKo


People also ask

How do I crop a picture into a square?

To Select a Square to CropClick the shape (or the arrow beneath Shapes) and choose the rectangle. 2. Hold down your shift key and use your mouse to draw the size square you need. 3.


1 Answers

Expanding a little on the answer above

Since in some situations you can end up with an exception or not the expected result, just by using the Bitmap.createBitmap(), like the fallowing:

java.lang.IllegalArgumentException: x + width must be <= bitmap.width()

Heres is a small function that does the crop and handle some of the commons cases.

Edit: updated accordantly to droidster's claim.

public static Bitmap cropToSquare(Bitmap bitmap){
    int width  = bitmap.getWidth();
    int height = bitmap.getHeight();
    int newWidth = (height > width) ? width : height;
    int newHeight = (height > width)? height - ( height - width) : height;
    int cropW = (width - height) / 2;
    cropW = (cropW < 0)? 0: cropW;
    int cropH = (height - width) / 2;
    cropH = (cropH < 0)? 0: cropH;
    Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);

    return cropImg;
}

I did several testing with some images of different resolutions and sizes and it work as expected.

It can also be used in other situations, for example when you are trying to make a "perfectly" round image and need to pass a squarish bitmap, etc.

like image 130
cass Avatar answered Sep 20 '22 20:09

cass