Image Compression with Node.js and Sharp
Making a node js project to compress images
Introduction:
Images play a crucial role in driving traffic to your website. However, using large images can impact your response time. For example, if your website allows users to upload pictures, they might inadvertently upload large images, slowing down your website and consuming more server space. This is where image compression comes in—a method to enhance and edit images, optimizing them for the web.
Prerequisites:
To complete this tutorial, you need:
Node.js installed in your local development environment.
Basic knowledge of Node.js.
Step 1 - Setting up the project:
Before diving into image compression, set up your Node.js project using npm or yarn:
npm init -y
The -y
option creates a basic version of the package.json
. Next, install the sharp
library:
npm install sharp
Download the image you want to compress and add it to your project's root folder (e.g., image.png
).
Step 2 - Image Compression:
Create a file named resizeImage.js
and open it. Import sharp
into the file:
const sharp = require('sharp');
Add the following code to the file:
async function resizeImage(imageFile, property) {
try {
await sharp(imageFile)
.resize({
width: property.width,
height: property.height,
})
.toFile(property.fileName);
} catch (error) {
console.log(error);
}
}
module.exports = { resizeImage };
This function resizes images to the desired width and height.
To use it, create an index.js
file:
const { resizeImage } = require('./resizeImage.js');
resizeImage('image.png', {
width: 100,
height: 100,
fileName: 'new-image.png',
});
Here, width
and height
represent the dimensions of the image, and fileName
is the new edited picture's filename.
Conclusion:
In this tutorial, you learned how to compress an image using Node.js and the sharp
library. You set up your project with npm or yarn, installed the sharp
library, created an imageResize
function for resizing images, and implemented it in index.js
to resize image.png
to new-image.png
with a width and height of 100.
For more documentation on sharp
, refer to the official documentation.
How does that look?