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:
Next, install the required packages:
The Code
Create a new file named resize.js
and add the following code:
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:
This will resize all JPEG images in the input directory and save the resized images in the output directory.