欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

nodejs批量裁剪图片尺寸大小

程序员文章站 2022-04-09 09:21:48
...

使用

$ node resetImage.js

依赖第三方库

$ npm install --save-dev sharp dotenv

代码

.env

# 图片存放的文件夹位置
AVATAR_PATH=./avatars/

# 裁剪图片存放的文件夹位置
SMALL_AVATAR_PATH=./small_avatars/

# 裁剪图片尺寸大小
SHARP_IMAGE_SIZE=200

# 非法图片汇总的文件
SURPLUS_IMAGE_PATH=surplusImage.txt

resetImage.js

const fs = require('fs')
const path = require('path')
const sharp = require('sharp')
require('dotenv').config()

// 忽略的文件
const IGNORE_FILE = ['.DS_Store']
const PNG_EXT = '.png'
const JPG_EXT = '.jpg'

const { AVATAR_PATH, SMALL_AVATAR_PATH, SHARP_IMAGE_SIZE, SURPLUS_IMAGE_PATH } = process.env

const fileList = fs.readdirSync(AVATAR_PATH)

if (!fs.existsSync(SMALL_AVATAR_PATH)) fs.mkdirSync(SMALL_AVATAR_PATH)

const savePngFile = (file, fileName) => sharp(`${AVATAR_PATH}${file}`).resize(Number(SHARP_IMAGE_SIZE)).png().toFile(`${SMALL_AVATAR_PATH}${fileName || file}`)

const surplusList = fileList.filter(file => {
  if (path.extname(file) === PNG_EXT) {
    savePngFile(file)
    // sharp(`${AVATAR_PATH}${file}`).resize(Number(SHARP_IMAGE_SIZE)).png().toFile(`${SMALL_AVATAR_PATH}${file}`)
  } else if (path.extname(file) === JPG_EXT) {
    // jpg格式转png格式保存
    const name = path.basename(file, JPG_EXT)
    savePngFile(file, `${name}${PNG_EXT}`)
    // sharp(`${AVATAR_PATH}${file}`).resize(Number(SHARP_IMAGE_SIZE)).jpeg().toFile(`${SMALL_AVATAR_PATH}${file}`)
  } else {
    // 不包括忽略文件并且不是文件夹,记录下来
    return !IGNORE_FILE.includes(file) && !fs.statSync(file).isDirectory()
  }
})

if (surplusList.length) fs.writeFileSync(SURPLUS_IMAGE_PATH, surplusList.join('\n'))

相关标签: javascript