node express 批量压缩图片

场景: 我是10万张图片(只压缩 png, jpg, jpeg)
分批次压缩, 因为压缩要内存限制,不能一次性压缩那么多

const fs = require('fs');
const path = require('path');
const images = require('images');
const express = require('express');
const app = express();

async function compressImages(dir, startIndex, endIndex) {
  const files = fs.readdirSync(dir);
  console.log('files', files.length);
  const batch = files.slice(startIndex, endIndex);
  console.log('batch', batch);
  await processBatch(batch, dir, startIndex);
  console.log('所有任务处理完成');
}

async function processBatch(batch, dir, startIndex) {
  for (let i = 0; i < batch.length; i++) {
    const file = batch[i];
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    // console.info(3333, filePath);
    if (filePath.endsWith('.webp')) {
    // 排除你不想要的图片格式
      continue;
    }
    if (!stat.isDirectory()) {
      const size = stat.size;
      let quality = getQuality(size);
      console.log(
        `正在处理:${startIndex + i + 1} => 压缩质量:${quality} => ${filePath}`
      );
      try {
        images(filePath).save(filePath, { quality });
      } catch (error) {
       // 错误直接忽略,执行下一条任务
        continue;
      }
    }
  }
}

function getQuality(size) {
  // console.log('传入图片大小Bt', size);
  let sizeKB = size / 1024;
  if (sizeKB <= 50) {
    // console.log('sizeKB <= 100', sizeKB);
    return 100;
  } else if (sizeKB > 50 && sizeKB <= 100) {
    // console.log('sizeKB <= 100', sizeKB);
    return 95;
  } else if (sizeKB > 100 && sizeKB <= 200) {
    // console.log('100 < sizeKB <= 200', sizeKB);
    return 80;
  } else if (sizeKB > 200 && sizeKB <= 500) {
    // console.log('200kb < sizeKB <= 500kb', sizeKB);
    return 60;
  } else if (sizeKB > 500 && sizeKB <= 1024) {
    // console.log('500kb < sizeKB <= 1M', sizeKB);
    return 50;
  } else if (sizeKB > 1024 && sizeKB <= 1024 * 2) {
    // console.log('1M < sizeKB <= 2M', sizeKB / 1024);
    return 40;
  } else if (sizeKB > 1024 * 2 && sizeKB <= 1024 * 3) {
    // console.log('2M < sizeKB <= 3M', sizeKB / 1024);
    return 30;
  } else if (sizeKB > 1024 * 3 && sizeKB <= 1024 * 5) {
    // console.log('3M < sizeKB <= 5M', sizeKB / 1024);
    return 20;
  } else {
    // console.log('sizeKB > 5M', sizeKB / 1024);
    return 10; // 压缩质量为20
  }
}

// 你需要将 'images/book' 替换为你要处理的文件夹的路径
// 你也需要设置 startIndex 和 endIndex
compressImages('images/book', 0, 5000);

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3922, function () {
  console.log('Example app listening on port 3922!');
});

你可能感兴趣的:(express,javascript,前端)