Skip to content

Sample code to resize and crop image

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageCropper {

    public static final int TARGET_WIDTH = 560;
    public static final int TARGET_HEIGHT = 168;

    public static void main(String[] args) {
        try {
            BufferedImage originalImage = ImageIO.read(new File("C://exchange/mypic.jpg"));
            cropImageToGivenSize(originalImage, TARGET_WIDTH, TARGET_HEIGHT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void cropImageToGivenSize(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
        System.out.println("Original Image Dimension: " + originalImage.getWidth() + "x" + originalImage.getHeight());

        float widthRatio = (float)originalImage.getWidth() / targetWidth;
        float heightRatio =(float)originalImage.getHeight() / targetHeight;

        BufferedImage resizedImage = originalImage;
        int resizedWidth = originalImage.getWidth();
        int resizedHeight = originalImage.getHeight();
        if(widthRatio > heightRatio){ //shrink to fixed height
            resizedWidth = Math.round(originalImage.getWidth() / heightRatio);
            resizedHeight = targetHeight;
        }else{ //shrink to fixed width
            resizedWidth = targetWidth;
            resizedHeight = Math.round(originalImage.getHeight() / widthRatio);
        }
        resizedImage = resizeImage(originalImage, originalImage.getType(), resizedWidth, resizedHeight);

        int startX = resizedWidth/2 - targetWidth/2;
        int startY = resizedHeight/2 - targetHeight/2;
        BufferedImage SubImage = resizedImage.getSubimage(startX, startY, targetWidth, targetHeight);
        System.out.println("Cropped Image Dimension: " + SubImage.getWidth() + "x" + SubImage.getHeight());

        File outputfile = new File("C://exchange/test_after_crop_2.jpg");
        ImageIO.write(SubImage, "jpg", outputfile);

        System.out.println("Image cropped successfully: "+outputfile.getPath());
    }

    private static BufferedImage resizeImage(BufferedImage originalImage, int type,
                                             Integer img_width, Integer img_height)
    {
        BufferedImage resizedImage = new BufferedImage(img_width, img_height, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, img_width, img_height, null);
        g.dispose();

        return resizedImage;
    }
}
%d bloggers like this: