HOWTO · Java
How to Crop Image in Java
This article will discuss how to crop an image in java, and for that, we will use the subimage function from the BufferedImage class to crop an image in Java.
On this page
Crop a rectangular part of an image in Java with BufferedImage.getSubimage(x, y, width, height), then write the returned image with ImageIO. The rectangle starts at its upper-left corner (x, y); its width and height determine how much of the source to keep.
Crop an Image with BufferedImage.getSubimage
BufferedImage represents an image whose pixels can be accessed in memory. Its getSubimage method returns a view of a rectangular region of that image. The arguments are x and y, the coordinates of the rectangle’s upper-left corner, followed by its width and height. The returned image has the requested dimensions and shares pixel data with the source image, so use a copy if later changes to either image must be independent.
Read an Image and Save the Cropped Result
Pass an input image path and an output path ending in .png as the program’s two arguments. With no arguments, the example creates a small sample PNG in a temporary directory so it can also demonstrate the complete flow without another file. It reads the selected input with ImageIO, crops the rectangle, and writes a PNG. Change the crop coordinates to fit your image.
Run this self-contained example:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) {
try {
Path inputPath;
Path outputPath;
if (args.length == 2) {
inputPath = Paths.get(args[0]);
outputPath = Paths.get(args[1]);
} else if (args.length == 0) {
Path folder = Files.createTempDirectory("java-crop-");
inputPath = folder.resolve("source.png");
outputPath = folder.resolve("crop.png");
BufferedImage sample = new BufferedImage(100, 80, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < sample.getHeight(); y++) {
for (int x = 0; x < sample.getWidth(); x++) {
sample.setRGB(x, y, (x < 50) ? Color.BLUE.getRGB() : Color.ORANGE.getRGB());
}
}
ImageIO.write(sample, "png", inputPath.toFile());
} else {
System.out.println("Provide both an input path and an output path.");
return;
}
if (!outputPath.getFileName().toString().toLowerCase().endsWith(".png")) {
System.out.println("The output path must end in .png.");
return;
}
BufferedImage source = ImageIO.read(inputPath.toFile());
if (source == null) {
System.out.println("The input format is not supported.");
return;
}
int x = 20;
int y = 15;
int width = 40;
int height = 30;
if (x < 0 || y < 0 || width <= 0 || height <= 0
|| x > source.getWidth() - width || y > source.getHeight() - height) {
System.out.println("The crop rectangle must fit inside the input image.");
return;
}
BufferedImage crop = source.getSubimage(x, y, width, height);
boolean written = ImageIO.write(crop, "png", outputPath.toFile());
if (written) {
System.out.println("Saved crop: " + crop.getWidth() + "x" + crop.getHeight());
} else {
System.out.println("No PNG writer is available.");
}
} catch (IOException ex) {
System.out.println("Image file operation failed: " + ex.getMessage());
}
}
}
Saved crop: 40x30
The selected source image is shown beside the resulting crop. These supplied images illustrate the visible effect of cropping a real image.
| Before | After |
|---|---|
|
|
Choose Crop Coordinates and Dimensions
Coordinates start at the source image’s upper-left corner: x increases to the right and y increases downward. In the example, (20, 15) is the crop’s starting point, and 40 by 30 is its size. For an image with width W and height H, choose nonnegative x and y, positive width and height, and ensure x + width <= W and y + height <= H. For example, a crop that starts at x = 20 and is 40 pixels wide ends at column 59, so the source must be at least 60 pixels wide.
Handle Invalid Inputs and Common Failures
ImageIO.read(File) can throw IOException when a file cannot be read. It can also return null when no registered reader recognizes the input format, so check for that before calling getSubimage. The example catches file-operation errors and checks whether a PNG writer was available; ImageIO.write(RenderedImage, String, File) returns false when it cannot write the requested format.
A crop rectangle outside the source image, or one with a nonpositive width or height, causes getSubimage to throw RasterFormatException; see the BufferedImage.getSubimage API documentation. Validate dimensions before the call, especially when coordinates come from user input. For the example, provide a writable output location and keep the PNG format name aligned with the .png filename.