To compress PNG and JPG images in Node.js, you can use the imagemin
library along with its plugins specifically designed for PNG (imagemin-pngquant
) and JPG (imagemin-mozjpeg
) compression. Here’s an example of how to use imagemin
in a Node.js script:
Step 1: Set up a new Node.js project
Create a new directory for your project and navigate into it. Open a terminal in the project directory.
Initialize a new Node.js project by running the following command:
npm init -y
Step 2: Install the required packages
Install the imagemin
, imagemin-pngquant
, and imagemin-mozjpeg
packages by running the following command:
`
npm install imagemin imagemin-pngquant imagemin-mozjpeg
Step 3: Create a compression script
Create a new JavaScript file (e.g., compress-images.js
) in the project directory and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
const imagemin = require('imagemin'); const imageminPngquant = require('imagemin-pngquant'); const imageminMozjpeg = require('imagemin-mozjpeg'); async function compressImages() { try { const files = await imagemin(['images/*.{jpg,png}'], { destination: 'compressed-images', plugins: [ imageminMozjpeg({ quality: 80 }), imageminPngquant({ quality: [0.6, 0.8] }) ] }); console.log('Images compressed successfully:'); console.log(files.map(file => file.destinationPath)); } catch (error) { console.error('Error compressing images:', error); } } compressImages(); |
In the code above, we import the required packages: imagemin
, imagemin-pngquant
, and imagemin-mozjpeg
.
The compressImages
function is an asynchronous function that performs the image compression. It uses the imagemin
function to compress the images in the images
directory and saves the compressed images in the compressed-images
directory.
The plugins
option is used to specify the plugins to be used for PNG and JPG compression. imageminMozjpeg
is used for JPG compression with a quality setting of 80, and imageminPngquant
is used for PNG compression with a quality range of 0.6 to 0.8.
The script then logs the paths of the compressed images to the console.
Step 4: Add images to compress
Create a new directory named images
in the project directory and add the PNG and JPG images that you want to compress.
Step 5: Run the compression script
Save the file and run the compression script by executing the following command in the terminal: