Image Processing API: How to Resize an Image & Preserve the Aspect Ratio
Aspect ratio is an important measurement for image and video files, and we don’t want that ratio to go away with every image resizing operation. One of our Image Resizing APIs handles this ratio-preserving operation with ease, and you can easily take advantage of it by following steps below to implement with Java.
Start by installing the Java SDK (instructions included in this article for Maven; instructions for Gradle are available on our API console documentation page). Add a reference to the pom.xml repository:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Next, add a reference to the dependency in pom.xml:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>
Finally, finish up by adding in the import classes and calling the 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.ResizeApi;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");ResizeApi apiInstance = new ResizeApi();
Integer maxWidth = 56; // Integer | Maximum width of the output image - final image will be as large as possible while less than or equial to this width
Integer maxHeight = 56; // Integer | Maximum height of the output image - final image will be as large as possible while less than or equial to this height
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.resizePost(maxWidth, maxHeight, imageFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ResizeApi#resizePost");
e.printStackTrace();
}