Image Processing API: How to Crop an Image to a Rectangular Area using Java

Cloudmersive
2 min readMay 3, 2022

Cropping images can be a tedious when that task involves opening each individual file. With our Image Cropping API, you can skip that step entirely. You can input common image file formats and crop them by specifying the new area of pixels (including height, width, etc.) to be found in the ensuing image.

You can take advantage of this API easily using code snippets & installation instructions provided below in Java, or alternatively visit our API platform to find code snippets available in several additional programming languages.

To start installation with Maven, begin by adding the following reference to the repository in pom.xml:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

After that, add one to the dependency:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

Finally, include the import classes and call the image processing function:

// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.EditApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
EditApi apiInstance = new EditApi();
Integer left = 56; // Integer | The left edge of the rectangular crop area in pixels (X).
Integer top = 56; // Integer | The top edge of the rectangular crop area in pixels (Y).
Integer width = 56; // Integer | The width of the rectangular crop area in pixels.
Integer height = 56; // Integer | The height of the rectangular crop area in pixels.
File imageFile = new File("/path/to/inputfile"); // File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try {
byte[] result = apiInstance.editCropRectangle(left, top, width, height, imageFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EditApi#editCropRectangle");
e.printStackTrace();
}

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.