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.

1
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * 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:

1
2
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:

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

where image is the cropped image.

Share this tutorial!