How to Crop and Rotate an Image in Java
Utilize Image APIs to automatically crop and rotate an image or photo
Join the DZone community and get the full member experience.Join For Free
Ever since our phones became a multi-purpose tool and included a high-quality camera as one of the features, photos have become an even more important and present aspect of our lives. We use photos to capture memories and moments that we would previously miss without a camera, and we also upload them as profile pictures to identify ourselves on various professional and social websites.
You’ve probably noticed that most sites that allow users to upload profile pictures automatically crop the image to a particular shape and/or angle; this is done behind the scenes and ensures image consistency across the site. Cropping, or the removal of a specific part of an image, can be performed for various reasons but most frequently its purpose is to zoom in on a certain part of the photo and removed unwanted or unnecessary objects/space. If your business has a website or application that allows users to upload images, it can be beneficial to set up some of these built-in parameters. To that end, the following tutorial will discuss how to use an API in Java to automatically rotate an image and/or crop the image to a circular or rectangular shape all while maintaining the aspect ratio.
Let’s kick off our image processing with the installation of the Maven SDK. First, we will need to add a reference to the repository:
Then, we’ll add a reference to the dependency:
Now we’re ready to call our first function, which is rotating an image. To perform this function, you will need to input the degrees to rotate the image (0-360), the target image file, and the API key. If you don’t already have an API key, you can retrieve it by registering for a free account on the Cloudmersive website.
Next, we will focus on how to crop an image to a circular shape. As mentioned earlier, this is ideal to use on images that are uploaded as profile pictures. To complete this function, add the imports to the top of the controller, and be sure to input the following parameters:
- Left – the left edge of the circular crop area in pixels
- Top – the top edge of the circular crop area in pixels
- Radius – the radius of the circular crop area in pixels
- File – the image file to perform the operation on
- API key – your personal API key
Alternatively, if you prefer to crop to a rectangular shape, you can call the following function. Similar to the process above you will need to input the file, API key, and dimensions – the dimensions for this process are the left edge, top edge, width, and height of the rectangular crop area in pixels.
Opinions expressed by DZone contributors are their own.