• How to Crop Image in Java

    Sometimes, you need to crop an image. In order to crop image in java, we will use the method subimage from BufferedImage class.

    bufferedImage.getSubimage(x, y, width, height);

    Example:
    This static method will return the cropped image given the starting x and y coordinate and the width and height that will be cropped from the image.

    /**
     * Crops an image to the specified region
     * @param bufferedImage the image that will be crop
     * @param x the upper left x coordinate that this region will start
     * @param y the upper left y coordinate that this region will start
     * @param width the width of the region that will be crop
     * @param height the height of the region that will be crop
     * @return the image that was cropped.
     */
    public static BufferedImage cropImage(BufferedImage bufferedImage, int x, int y, int width, int height){
        BufferedImage croppedImage = bufferedImage.getSubimage(x, y, width, height);
        return croppedImage;
    }


    To read an image from a file, we can do:

    File imageFile = new File("C:/Javapointers/image.jpg");
    BufferedImage bufferedImage = ImageIO.read(imageFile);
    

    This method will return the image buffered from the file.

    After cropping the image, we can now save or write the file to the file system using:

    File pathFile = new File("C:/Javapointers/image-crop.jpg");
    ImageIO.write(image,"jpg", pathFile);

    where image is the cropped image.

    Related Post