使用nodejs sharp遍历文件夹图片制作缩略图

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

const TargetImagesFolder="../vue/public/images";


function traverseFolder(folderPath, func) {
  const items = fs.readdirSync(folderPath);
  items.forEach(item => {
    const itemPath = path.join(folderPath, item);
    const stats = fs.statSync(itemPath);
    if (stats.isDirectory()) {
      traverseFolder(itemPath, func);
    } else if (stats.isFile()) {
      func(itemPath, folderPath, item);
    }
  });
}

function resize_image(p, folderPath, fileName){
  let small_folder=path.join(folderPath, 'small');
  if(!fs.existsSync(small_folder)){ fs.mkdirSync(small_folder); } else {
    const stats = fs.statSync(small_folder); 
    if (stats.isFile()) {
      console.log("cannot create small images folder, it's used by a file: ", small_folder);
      return;
    } 
  }  
  let small_path=path.join(small_folder, fileName); console.log(small_path);
  if(fs.existsSync(small_path)){ fs.unlinkSync(small_path); }
  sharp(p).resize(400).toFile(small_path, (err, info) => {  });
}
traverseFolder(TargetImagesFolder, resize_image);

以上如有错漏之处,敬请大家指正。我的联系方式:
微信:TobeBuda
Email/Paypal: jinmin.si@outlook.com
邀请您加入「社区资讯服务」创业微信群,共同探讨打造社区资讯服务的美好未来。

2024年6月3日

本文参考资料:
https://developer.aliyun.com/article/1324486

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiuzen

您的资助将帮助我创作更好的作品

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值