How to crop an image to a rectangle in Node.JS

Image cropping is easy enough from within any piece of photo editing software, but what about when we need to do it from within Node.JS? This becomes a little more challenging, but allows us to quickly crop large numbers of images. I’m going to show you a way to make this task much easier through the use of an API custom-built for the task.

Start by npm installing our API client through the use of this command:

npm install cloudmersive-image-api-client --save

Continuing on, we can call our function from said API with this code snippet here:

var CloudmersiveImageApiClient = require('cloudmersive-image-api-client');var defaultClient = CloudmersiveImageApiClient.ApiClient.instance;// Configure API key authorization: Apikeyvar Apikey = defaultClient.authentications['Apikey'];Apikey.apiKey = 'YOUR API KEY';// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.apiKeyPrefix = 'Token';var apiInstance = new CloudmersiveImageApiClient.EditApi();var left = 56; // Number | The left edge of the rectangular crop area in pixels (X).var top = 56; // Number | The top edge of the rectangular crop area in pixels (Y).var width = 56; // Number | The width of the rectangular crop area in pixels.var height = 56; // Number | The height of the rectangular crop area in pixels.var imageFile = "/path/to/file"; // File | Image file to perform the operation on.  Common file formats such as PNG, JPEG are supported.var callback = function(error, data, response) {if (error) {console.error(error);} else {console.log('API called successfully. Returned data: ' + data);}};apiInstance.editCropRectangle(left, top, width, height, imageFile, callback);

As you can see from the comments, you may specify your crop parameters with the coordinates of the top left corner, followed by the width and height of your rectangle. You could easily set these numbers to be based on a percentage of each image’s overall size, or use it to make a single size for thumbnails or uniform sized web display. However you use it, the function is ready to go.

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