How to rotate an image in Node Jimp?


NodeJS – Rotate() is an inbuilt function that is used to rotate the images. The image is rotated clockwise where the dimensions of the image remains same and no changes are made on them.

Syntax

rotate ( r, mode, cb )

Definition of rotate() paramters

  • r – Used to store the rotation angle at which the image will be rotated.

  • mode – Used to store the scaling method of the image. This is an optional parameter.

  • cb – This is an optional parameter that can be invoked after the compilation is complete.

Input Image

Using Node JIMP – ROTATE()

Before proceeding to use rotate() functions, please check that the following statements are already executed for setting up the environment.

  • npm init -y // Initialising the Node environment

  • npm install jimp --save // Installing the jimp dependency

  • Create a rotate.js file and copy-paste the following code snippet in it.

  • Use node rotate.js to run the code.

Note – The method name should match with the JS file name. Only then, it will be able to call the desired method.

Example

const Jimp = require('jimp') ;

async function rotate() {
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   // Checking if any error occurs while rotating image
   image.rotate(300, function(err){
      if (err) throw err;
   })
   .write('/home/jimp/rotate.jpg');
}

rotate();
console.log("Image is processed successfully");

Output

Using Node JIMP – ROTATE() with 'cb' optional parameters

Example

const Jimp = require('jimp') ;

async function rotate() {
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   // Checking if any error occurs while rotating image
   image.rotate(159, Jimp.RESIZE_BEZIER, function(err){
      if (err) throw err;
   })
   .write('/home/mayankaggarwal/mysql-test/rotate.jpg');
}

rotate();
console.log("Image is processed successfully");

Output

Updated on: 27-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements