What is pngquant-bin?
The pngquant-bin npm package provides a Node.js wrapper for the pngquant command-line tool, which is used to compress PNG images. It allows developers to reduce the file size of PNG images while maintaining a balance between quality and compression.
Compress PNG images
This feature allows you to compress PNG images by specifying the quality range. The code sample demonstrates how to use the pngquant-bin package to compress an image named 'input.png' and save the compressed version as 'output.png'.
const pngquant = require('pngquant-bin');
const { execFile } = require('child_process');
execFile(pngquant, ['--quality=65-80', 'input.png', '-o', 'output.png'], err => {
if (err) {
throw err;
}
console.log('Image compressed successfully');
});
Batch processing of PNG images
This feature allows you to compress multiple PNG images in a directory. The code sample demonstrates how to read all files in the 'images' directory, compress each one, and save the compressed versions in the 'compressed_images' directory.
const pngquant = require('pngquant-bin');
const { execFile } = require('child_process');
const fs = require('fs');
const path = require('path');
const inputDir = 'images';
const outputDir = 'compressed_images';
fs.readdir(inputDir, (err, files) => {
if (err) {
throw err;
}
files.forEach(file => {
const inputFile = path.join(inputDir, file);
const outputFile = path.join(outputDir, file);
execFile(pngquant, ['--quality=65-80', inputFile, '-o', outputFile], err => {
if (err) {
throw err;
}
console.log(`${file} compressed successfully`);
});
});
});