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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay