How to crop an image outside it's original boundaries

45 views Asked by At

I have an image of a face that's a narrow rectangle and I want to crop a square image centered on the face so that the bounds of the cropped image extend beyond the boundaries of the original image.

Here's an example, the green box is the boundary of the original image and the red box is the desired boundary of the new image.

How do I perform this "crop" in Java?

enter image description here

Currently this is what I'm doing, but imgscalr wouldn't let me crop outside the bounds of the original image.

static BufferedImage crop(BufferedImage bufferedImage, BoundingBox box) {
    int y = box.top as Integer
    int x = box.left as Integer
    int targetWidth = box.width as Integer
    int targetHeight = box.height as Integer

    Scalr.crop(bufferedImage, x, y, targetWidth - 1, targetHeight)
}
1

There are 1 answers

0
SGT Grumpy Pants On

Padding the image before cropping solved the problem

static BufferedImage pad(BufferedImage bufferedImage) {
    int padding = Math.min(bufferedImage.height, bufferedImage.width) / 2
    BufferedImage paddedImage = Scalr.pad(bufferedImage, padding, Color.WHITE)
    return paddedImage
}

Then I cropped the padded image.

Thanks, everyone for the help in the comments.