2024-09-30 Web Development
Resizing JPEG Images with Node.js and Sharp
By O Wolfson
In this article describes how to resize JPEG images using Node.js, the sharp
library, and fs-extra
for file system operations. This script will read JPEG files from a specified input directory, resize them to a width of 2000 pixels while maintaining the aspect ratio, and save the resized images to an output directory.
Prerequisites
To follow along, you need Node.js installed on your machine. You can download it from nodejs.org.
Setting Up the Project
First, create a new directory for your project and initialize a new Node.js project:
bashmkdir image-resizer
cd image-resizer
npm init -y
Next, install the required packages:
bashnpm install sharp fs-extra
The Code
Create a new file named resize.js
and add the following code:
javascriptconst fs = require("fs");
const path = require("path");
const sharp = require("sharp");
const fsExtra = require("fs-extra");
const inputDirectory = "/path/to/jpegs";
const outputDirectory = "/path/to/jpegs/scaled";
// Ensure the output directory exists
fsExtra.ensureDirSync(outputDirectory);
// Function to resize JPEG images
async function resizeJpegImage(inputPath, outputPath) {
try {
await sharp(inputPath)
.resize({ width: 2000 }) // Adjust the width to 2000px, maintaining aspect ratio
.jpeg({ quality: 70 }) // Adjust the quality as needed
.toFile(outputPath);
console.log(`Resized ${inputPath} to ${outputPath}`);
} catch (error) {
console.error(`Error resizing ${inputPath}:`, error);
}
}
// Process all JPEG files in the input directory
fs.readdir(inputDirectory, (err, files) => {
if (err) {
console.error("Error reading input directory:", err);
return;
}
files.forEach((file) => {
if (
file.toLowerCase().endsWith(".jpg") ||
file.toLowerCase().endsWith(".jpeg")
) {
const inputPath = path.join(inputDirectory, file);
const outputFilename =
path.basename(file, path.extname(file)) + "_2k.jpg";
const outputPath = path.join(outputDirectory, outputFilename);
resizeJpegImage(inputPath, outputPath);
}
});
});
Explanation
-
Importing Modules: We start by importing the required modules:
fs
for file system operations.path
for handling and transforming file paths.sharp
for image processing.fs-extra
for additional file system operations.
-
Setting Up Directories: We define the input and output directories. The input directory contains the original JPEG images, and the output directory will store the resized images.
-
Ensuring Output Directory: We use
fsExtra.ensureDirSync
to ensure the output directory exists. If it doesn't, it will be created. -
Resizing Function: The
resizeJpegImage
function usessharp
to resize an image to a width of 2000 pixels, maintaining the aspect ratio. The resized image is then saved with a quality of 70%. -
Processing Images: We read the input directory and filter for JPEG files. For each JPEG file, we generate an output path with "_2k" appended to the filename and call the
resizeJpegImage
function.
Running the Script
To run the script, execute the following command in your terminal:
bashnode resize.js
This will resize all JPEG images in the input directory and save the resized images in the output directory.