How to crop an image to a rectangle in Java

Image cropping is an essential function of any photo app worth its salt. Implementing it can be a little tricky to do manually, which is why today’s tutorial covers how to use an API to simplify this task. All in all, it should just take a few minutes, so let us begin.

To set up our library with Jitpack, we will need to add these references to pom.xml.





Now we will use the following snippet to call editCropRectangle. We may use this to define the top and left edge coordinates of our desired rectangle, as well as its dimensions.

// 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: ApikeyApiKeyAuth 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/file"); // 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();}

And that’s it! We are all done. If you would like similar functions in the same easy package, be sure to check out our documentation for such features as image rotation, format conversion, and dynamic gamma adjustment.

Image for post

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store