How to rotate an image a set number of degrees in Java
Image rotation is a useful tool to have at your disposal, but setting up an automated version for use in an app or for large numbers of images can be time consuming. This post will demonstrate how to accomplish this without the headache. Got 5 minutes? Because that’s all its going to take!
First, we need to use Jitpack to dynamically set up our library, which will require us to add two references to Maven POM.
Repository
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Dependency
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>
Now, simply call editRotate, provide an image, and specify a number of degrees of rotation.
// 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();Double degrees = 3.4D; // Double | Degrees to rotate the image; values range from 0.0 to 360.0.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.editRotate(degrees, imageFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling EditApi#editRotate");e.printStackTrace();}
That’s it! APIs really make things simple, don’t they? Some of our other functions allow for similarly useful image editing functions, including cropping, contrast adjustment, format conversion, and text insertion.