Apr 5, 2020

2 min read

How to invert or negate the colors in an image using Node.JS

There are a lot of good uses for color inversion/negation. Apart from overall assessment, it’s can be a nice stylistic choice or photo filter. Regardless of how you intend to use it, I’m going to show you the easiest way to implement it. Forget all the color theory and math you were about to apply to the problem, we are going the easy path today. Here’s how to get it done with an API.

Before we do anything else, we need to install our API client. Use this snippet in your package.json file.

"dependencies": {
"cloudmersive-image-api-client": "^1.2.3"

Now call the invert function:

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 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.editInvert(imageFile, callback);

Done! Now we can test it out. I used this image for my test:

And here is the inverted version: