Crop Images in Java

In the previous blog posts, we have shown you how to implement various image editing features such as resizing, flipping and rotating images. Along with these features, image cropping is immensely used to trim the unwanted areas in the images. Also, you crop an image to focus on a particular object in the frame. In this article, you will learn how to crop images programmatically in Java. We will demonstrate how to crop an image using shift values or with a rectangle.

Java API to Crop Images - Free Download

Aspose.Imaging for Java is an amazing image editing API that provides a wide range of features to manipulate images. In addition, it supports a variety of raster and vector image formats. We will use this API to crop the images from within our Java application. You can either download the API or install it using the following Maven configurations.

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>https://repository.aspose.com/repo/</url>
</repository> 

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-imaging</artifactId>
    <version>22.9</version>
</dependency>

Crop Images in Java

There are two ways to crop a raster image: shift values and rectangle. In the first method, we need to provide left, right, top and bottom shift values to crop an image. Whereas, in the second method, we define a rectangle to crop a certain area of an image.

Let’s have a look at each of the above-mentioned methods to crop images in Java.

Crop Images with Shift Values in Java

The following are the steps for cropping an image using shift values in Java.

The following code sample shows how to crop an image in Java.

The following is the input image that we used for cropping.

crop image in Java

Below is the resultant cropped image.

image cropping in Java

Java Image Cropping using Rectangle

You can also define a rectangle to crop the desired area of an image. The following steps demonstrate image cropping using a rectangle in Java.

The following code sample shows how to perform image cropping with a rectangle in Java.

Imaging Cropping API for Java - Get a Free License

You can get a free temporary license and crop images without evaluation limitations.

Conclusion

In this article, you have learned how to crop images in Java. We have demonstrated a couple of ways to crop an image using shift values or a rectangle. In addition, you can explore more about the Java image processing API using documentation. Also, you can share your queries with us via our forum.

See Also