Node实现图片自动压缩

npm install image-size  sharp

const fs = require('fs')
const path = require('path')
const sharp = require('sharp')
const sizeOf = require('image-size')

// 输入文件夹路径
const inputFolder = 'D:/40705/Desktop/123/Nut'

// 输出文件夹路径
const outputFolder = 'D:/40705/Desktop/Nut/'

// 目标压缩大小(以字节为单位)
const targetSize = 500 * 1024 // 500 KB

// 递归处理文件夹
function processFolder(folderPath) {
  const files = fs.readdirSync(folderPath)

  files.forEach(file => {
    const filePath = path.join(folderPath, file)

    if (fs.statSync(filePath).isDirectory()) {
      // 如果是文件夹,则递归处理
      const subFolderOutput = path.join(outputFolder, path.relative(inputFolder, filePath))
      fs.mkdirSync(subFolderOutput, { recursive: true })
      processFolder(filePath)
    } else if (isImageFile(filePath)) {
      // 如果是图片文件,则进行压缩
      const outputFilePath = path.join(outputFolder, path.relative(inputFolder, filePath))
      compressImage(filePath, outputFilePath)
    }
  })
}

// 检查是否为支持的图片文件类型
function isImageFile(filePath) {
  const supportedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'] // 可以根据需要扩展
  const ext = path.extname(filePath).toLowerCase()
  return supportedExtensions.includes(ext)
}

// 压缩图片
function compressImage(inputFilePath, outputFilePath) {
  // 使用 image-size 获取图片尺寸
  const dimensions = sizeOf(inputFilePath)
  const originalSize = fs.statSync(inputFilePath).size

  // 计算压缩比例
  const scaleFactor = Math.sqrt(targetSize / originalSize)

  // 使用 sharp 进行图片压缩
  sharp(inputFilePath)
    .resize(Math.round(dimensions.width * scaleFactor), Math.round(dimensions.height * scaleFactor))
    .toFile(outputFilePath, (err, info) => {
      if (err) {
        console.error(`Error compressing image ${inputFilePath}:`, err)
      } else {
        console.log(`Image ${inputFilePath} compressed successfully.`)
      }
    })
}

// 开始处理文件夹
processFolder(inputFolder)

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值