node squoosh 壓縮圖片

squoosh使用node進(jìn)行圖片壓縮

// 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();

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容