DEV Community

Cover image for Rotating Images with Node.js Made Easy: Automate BoreStuffs
Akshay S
Akshay S

Posted on

Rotating Images with Node.js Made Easy: Automate BoreStuffs

Are you looking to automate the process of rotating images using Node.js? Look no further! In this guide, we'll walk through a simple script that utilizes the Jimp library to effortlessly rotate images.

Getting Started

First things first, let's ensure you have Node.js installed on your machine. If not, head over to Node.js website and follow the installation instructions.

Next, create a new directory for your project and initialize it with npm:

mkdir image-rotation
cd image-rotation
npm init -y
Enter fullscreen mode Exit fullscreen mode

This will create a package.json file where we'll manage our project dependencies.

Installing Dependencies

We'll need two main dependencies for this project: Jimp for image processing and fs for file system operations. Let's install them:

npm install jimp fs
Enter fullscreen mode Exit fullscreen mode

The Code

Now, let's dive into the code. Below is a simplified version of a Node.js script that rotates images within a specified directory by 180 degrees:

// Import required modules
var Jimp = require("jimp");
const fs = require('fs');

// Define the directory path where images are located
const directoryPath = ""; // Specify your directory path here
const rotateDeg = 180; // Define the rotation angle

// Function to get files in the directory
const getTheFilesInTheDir = (dir, callback) => {
    fs.readdir(dir, function (err, files) {
        if (err) {
            console.log('Unable to scan directory: ' + err);
            callback(err, null);
        } else {
            console.log("getTheFilesInTheDir", { files });
            callback(null, files);
        }
    });
}

// Function to rotate an image
const rotateImage = (filePath) => {
    Jimp.read(filePath, (err, image) => {
        if (err) throw err;
        console.log("RotatedImage:", filePath);
        image.rotate(180).write(filePath); // Rotate the image by 180 degrees
    });
}

// Function to initiate the rotation process
const initRotate = async () => {
    getTheFilesInTheDir(directoryPath, async (err, files) => {
        if (err) {
            console.log("Error:", error);
            return;
        }
        console.log("Files:", files);
        for (const file of files) {
            const path = directoryPath + "/" + file;
            const ext = file.split('.');
            if(ext[ext.length - 1] === 'webp'){
                // Skip rotating WebP files, if any specific handling is required, add it here
            } else {
                await rotateImage(path); // Rotate non-WebP images
            }
        }
    });
}

// Call the function to initiate rotation
initRotate();
Enter fullscreen mode Exit fullscreen mode

Explanation

  • We start by importing necessary modules: Jimp for image manipulation and fs for file system operations.
  • directoryPath variable holds the path to the directory containing the images to be rotated.
  • getTheFilesInTheDir function reads the files in the specified directory.
  • rotateImage function takes a file path, reads the image using Jimp, rotates it by 180 degrees, and saves it.
  • initRotate function orchestrates the rotation process by getting the files in the directory and iterating through them to rotate each one.
  • We check the file extension to skip rotating WebP images if present, but you can customize this behavior as needed.

Conclusion

And that's it! You've just created a simple Node.js script to rotate images effortlessly. Feel free to modify the code according to your specific requirements and integrate it into your projects. Happy coding!

Top comments (0)