By Alvin Alexander. Last updated: June 4, 2016
Java image FAQ: How do I crop an image in Java?
To crop an image in Java, just use the Java BufferedImage
class, specifically the getSubimage
method of the BufferedImage
class.
For instance, if you have a BufferedImage
named originalImage
, and you want to crop that image, just use a little Java code like this:
// create a cropped image from the original image BufferedImage croppedImage = originalImage.getSubimage(x, y, width, height);
Now just use this croppedImage
instead of the original image. As you can see, the key to this solution is using the getSubImage
method of the BufferedImage
class.
As mentioned in the BufferedImage
Javadoc, the four getSubimage
method parameters shown in the example above are defined as follows:
x - the X coordinate of the upper-left corner of the specified rectangular region y - the Y coordinate of the upper-left corner of the specified rectangular region width - the width of the specified rectangular region height - the height of the specified rectangular region
For more information on how to crop an image in Java, here's a link to the Java BufferedImage Javadoc.