I have never worked with pictures in java and I am a beginner in this. I need to make a function that will crop the images according to a certain ratio of width and height in the middle of the image.
Through REST Api I receive a MultipartFile which I pass to the image cropping function. I forward the image using file.getBytes().
Here is how I wrote the code for image crop function:
public static byte[] cropImage(byte[] data) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
try {
BufferedImage img = ImageIO.read(bais);
int width = img.getWidth();
int height = img.getHeight();
float aspectRatio = (float) 275 / (float) 160;
int destWidth;
int destHeight;
int startX;
int startY;
if(width/height > aspectRatio) {
destHeight = height;
destWidth = Math.round(aspectRatio * height);
startX = Math.round(( width - destWidth ) / 2);
startY = 0;
} else if (width/height < aspectRatio) {
destWidth = width;
destHeight = Math.round(width / aspectRatio);
startX = 0;
startY = Math.round((height - destHeight) / 2);
} else {
destWidth = width;
destHeight = height;
startX = 0;
startY = 0;
}
BufferedImage dst = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_ARGB);
dst.getGraphics().drawImage(img, 0, 0, destWidth, destHeight, startX, startY, startX + destWidth, startY + destHeight, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(dst, "png", baos);
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("IOException in scale");
}
}
But when I crop the image the result is an image with a much larger size than the received image. I need help on how to solve this problem.
EDIT:
According to this answer, the size increases on this part of the code:
ImageIO.read (bais)
Is there any other way to convert an image from byte array to buffered image but keep the size of the original image?
I don’t know why, but the problem was in part ImageIO.write(dst, "png", baos);
I was trying with different types of images (png, jpg, jpeg) and only with png
did it reduce my image size. While in the situation when I changed to jpeg
it reduced the size in all images.