Node.js 实现图片压缩 JPG / PNG(PNG效果一般)

node图片压缩

源文件放在images文件夹中

压缩后的文件放在compress文件夹中

// 使用第三方模块 images实现

// 关键源码解析 resize 方法支持只传宽度  高度自适应
const image = require('images')
image(被压缩图片路径).resize(宽, 高).save(压缩后的文件存放路径, {
  quality: 75, // 压缩质量
})

示例

const image = require('images')
const fs = require('fs')
const path = require('path')

const sourceFilePath = path.resolve(__dirname, './images') // 源文件路径
const compressPath = pt => path.resolve(pt.replace(/[\\|/]images[\\|/]/, '/compress/')) // 压缩后的路径

const supportSuffix = ['.png', '.jpg', '.JPG', '.PNG'] // 支持的文件后缀
function handleCompress(pt) {
  try {
    // 读取文件夹下的所有文件
    fs.readdir(pt, (err, sourceFiles) => {
      if (err) return
      // 遍历所有文件
      for (let i = 0; i < sourceFiles.length; i++) {
        const fileName = sourceFiles[i]
        const filePath = path.resolve(pt, fileName)
        // 获取文件的stat对象
        const stat = fs.statSync(filePath)
        // 如果是文件夹则递归调用
        if (stat.isDirectory()) {
          // 判断压缩后的文件夹不存在创建文件夹
          if (!fs.existsSync(filePath)) fs.mkdirSync(compressPath(filePath))
          handleCompress(filePath)
        } else if (supportSuffix.includes(path.extname(filePath))) {
          // 不是文件夹则压缩,并且在支持的文件后缀内则进行复制压缩
          fileCompress(filePath, fileName)
        }
      }
    })
  } catch (error) {
    console.log(error)
  }
}
function fileCompress(pt, fileName) {
  const { width, height } = image(pt).size() // 获取文件的宽高
  let quality = 75 //压缩图片质量
  const targetPath = compressPath(pt) // 压缩后的图片存放路径
  if (fs.existsSync(targetPath)) return // 发现文件已经存在 跳过
  // 执行压缩
  image(pt).resize(4500).save(targetPath, {
    quality: quality,
  })
}

// 调用
handleCompress(sourceFilePath)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值