squoosh使用node进行图片压缩
// import { ImagePool } from '@squoosh/lib';
// import fs from 'fs/promises';
const squoosh = require('@squoosh/lib');
const fs = require('fs');
const path = require('path');
const { ImagePool } = squoosh;
async function libSquooshOptimize(imagePath, filename, outputFolderPath) {
const imagePool = new ImagePool();
const image = await imagePool.ingestImage(imagePath);
const preprocessOptions = {
resize: {
width: 100,
},
};
await image.preprocess(preprocessOptions);
const encodeOptions = {
mozjpeg: {}, // an empty object means 'use default settings'
jxl: {
quality: 90,
},
};
await image.encode(encodeOptions);
const { extension, binary } = await image.encodedWith.mozjpeg;
fs.writeFileSync(`${outputFolderPath}/${filename}.${extension}`, binary);
imagePool.close();
}
async function libSquooshWebpOptimize(imagePath) {
const imagePool = new ImagePool();
const image = await imagePool.ingestImage(imagePath);
const preprocessOptions = {
resize: {
width: 100,
},
};
await image.preprocess(preprocessOptions);
const encodeOptions = {
webp: {
lossless: true,
method: 6,
},
};
await image.encode(encodeOptions);
const outFile = `${imagePath}.webp`;
const rawData = (await image.encodedWith.webp).binary;
fs.writeFileSync(outFile, rawData);
imagePool.close();
}
async function main() {
// Get input and output folders from arguments
const appArgs = process.argv.slice(2);
if (appArgs.length === 1) {
const inputFilePath = appArgs[0];
await libSquooshWebpOptimize(inputFilePath);
}
if (appArgs.length === 2) {
const inputFilePath = appArgs[0];
const outputFolderPath = appArgs[1];
const filename = path.basename(inputFilePath).replace(/\.[^/.]+$/, '');
await libSquooshOptimize(inputFilePath, `${filename}Optimize`, outputFolderPath);
}
// node build-webp.js test.jpg results
// await libSquooshOptimize(inputFilePath, `${filename}Optimize`, outputFolderPath);
console.log('Invalid command: Include <input> and <output> directories when calling this script.');
console.log('For example: node index.js images/ results/');
process.exit();
}
main();
网友评论