// Get the original image size
int imageWidth = imageInfo.getImageWidth();
int imageHeight = imageInfo.getImageHeight();
// Prepare for processing
ConvertCmd imageMagick = new ConvertCmd();
// Resizing
float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style);
int scaledWidth = Math.round(scale * imageWidth);
int scaledHeight = Math.round(scale * imageHeight);
int cropX = 0;
int cropY = 0;
// If either one of scaledWidth or scaledHeight is < 1.0, then
// the scale needs to be adapted to scale to 1.0 exactly and accomplish
// the rest by cropping.
if (scaledWidth < 1.0f) {
scale = 1.0f / imageWidth;
scaledWidth = 1;
cropY = imageHeight - scaledHeight;
scaledHeight = Math.round(imageHeight * scale);
} else if (scaledHeight < 1.0f) {
scale = 1.0f / imageHeight;
scaledHeight = 1;
cropX = imageWidth - scaledWidth;
scaledWidth = Math.round(imageWidth * scale);
}
// Do the scaling
IMOperation scaleOp = new IMOperation();
scaleOp.addImage(originalFile.getAbsolutePath());
scaleOp.resize((int) scaledWidth, (int) scaledHeight);
scaleOp.addImage(scaledFile.getAbsolutePath());
imageMagick.run(scaleOp);
finalFile = scaledFile;
// Cropping
cropX = (int) Math.max(cropX, Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style)));
cropY = (int) Math.max(cropY, Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style)));
if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) {
int croppedLeft = (int) (cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f);
int croppedTop = (int) (cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f);
int croppedWidth = (int) (scaledWidth - Math.max(cropX, 0.0f));
int croppedHeight = (int) (scaledHeight - Math.max(cropY, 0.0f));
// Do the cropping
IMOperation cropOperation = new IMOperation();
cropOperation.addImage(scaledFile.getAbsolutePath());
cropOperation.crop(croppedWidth, croppedHeight, croppedLeft, croppedTop);
cropOperation.p_repage(); // Reset the page canvas and position to match
// the actual cropped image
cropOperation.addImage(croppedFile.getAbsolutePath());
imageMagick.run(cropOperation);
finalFile = croppedFile;
}
// Write resized/cropped image encoded as JPEG to the output stream
FileInputStream fis = null;