sharp文件压缩脚本

使用方法:

package.json - scripts 添加一条命令

"sharp": "node script/sharp.js"

脚本代码:


const sharp = require('sharp');
const fs = require('fs');
const path = require('path');

// 定义图片格式
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif'];

// 压缩图片
function compressImage(filePath) {
  // 获取文件扩展名
  const extension = path.extname(filePath);
  // 判断是否为图片格式
  if (!imageExtensions.includes(extension)) {
    return;
  }
  
  // 读取图片
  const oldsize = fs.statSync(filePath).size;
  try {
    const image = sharp(filePath).png({ quality: 10 })
    // 获取图片元数据
    image.metadata().then(metadata => {
      // 将图片转换为buffer
      image.toBuffer().then(buffer => {
        // 将buffer写入文件
        fs.writeFileSync(filePath, buffer);
        const newSize = fs.statSync(filePath).size;
        console.log(`压缩图片成功,原大小:${oldsize},新大小:${newSize}`);
      });
    });
  } catch (error) {
    console.log('压缩图片失败', error);
  }

}

// 遍历目录
function traverseDirectory(directoryPath) {
  // 获取目录下的所有文件
  const files = fs.readdirSync(directoryPath);
  // 遍历文件
  files.forEach(file => {
    // 获取文件路径
    const filePath = path.join(directoryPath, file);
    // 获取文件状态
    const stats = fs.statSync(filePath);
    // 判断是否为目录
    if (stats.isDirectory()) {
      // 如果是目录,则继续遍历
      // 只遍历src目录
      if (filePath.includes('/src')) {
        traverseDirectory(filePath);
      }
    } else {
      // 如果是文件,则判断是否为src文件下的文件
      if (filePath.includes('/src/')) {
        // 获取文件扩展名
        const fileType = path.extname(filePath)
        // 判断是否为图片格式
        const isImage = imageExtensions.includes(fileType);
        // 如果是图片格式,则压缩图片
        if (isImage) {
          compressImage(filePath);
        } else {
          // console.log('不是图片格式', filePath);
        }
      }
    }
  });
}

// 遍历项目目录
traverseDirectory(path.join(__dirname, '../'));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值