I would like to show an image in all sort of placements with different width and height.
I am using a method for crop and resize with Sclar, But I have 2 problems:
- The result doesn't look so good in some cases. I think it is because the image in the code is first scaled.
- I get an exception in other cases. For example:
Invalid crop bounds: x [32], y [-1], width [64] and height [64] must all be >= 0
What is the best way of resizing a cropping and image to some target width and height?
Here is my current method:
public static BufferedImage resizeAndCropToCenter(BufferedImage image, int width, int height) {
image = Scalr.resize(image, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_WIDTH,
width * 2, height * 2, Scalr.OP_ANTIALIAS);
int x, y;
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
if (imageWidth > imageHeight) {
x = width / 2;
y = (imageHeight - height) / 2;
} else {
x = (imageWidth - width) / 2;
y = height / 2;
}
return Scalr.crop(image, x, y, width, height);
}