源代码 (resizex.JS)
- // 文件路径: resizex.JS
- // 安装并引用 images 模块处理图片瘦身
- const mimages = require('images')
- // 引用 fs 文件系统模块
- const mfs = require('fs')
- // 引用 path 路径处理模块
- const mpath = require('path')
- // 配置信息
- const config = {
- image_exts: ['jpg', 'png', 'gif', 'jpeg', 'webp', 'tiff'],
- }
- /**
- * 批量生成缩略图到指定目录 (目标目录的层级结构和来源目录保持一致)
- * @param {String} fromDir 来源目录
- * @param {String} toDir 目标目录
- * @param {Number} width 图片宽度
- * @param {Number} quality 图像质量
- */
- async function resizeImages(fromDir, toDir, width = 1080, quality = 80) {
- if (!mfs.existsSync(fromDir)) {
- console.log('path not exists:', fromDir);
- return;
- }
- // 自动创建目标路径
- if (!mfs.existsSync(toDir)) {
- mfs.mkdirSync(toDir, { recursive: true });
- }
- // 自动补齐路径符
- if (!fromDir.endsWith('/')) {
- fromDir += '/';
- }
- if (!toDir.endsWith('/')) {
- toDir += '/';
- }
- // 打开目录
- const dir = await mfs.promises.opendir(fromDir);
- // 声明变量, 优化内存
- let ext = '', newPath ='', currentPath = '';
- for await (const dirent of dir) {
- // 当前路径
- currentPath = fromDir + dirent.name;
- newPath = toDir + dirent.name;
- // 处理目录
- if (dirent.isDirectory()) {
- // 如果当前路径是目录, 则进入递归模式
- resizeImages(currentPath + '/', newPath + '/');
- continue;
- }
- // 处理文件
- ext = mpath.extname(dirent.name); // .jpg
- if (!ext) {
- continue;
- }
- ext = ext.substring(1).toLowerCase();
- if (!config.image_exts.includes(ext)) {
- continue;
- }
- // 重设图片尺寸并保存
- mimages(currentPath).resize(width).save(newPath, { quality: quality });
- console.log(currentPath, '缩略图', newPath);
- }
- }
- // 执行批量照片瘦身功能
- resizeImages('./a/', './c/').catch(err => console.log(err))
执行
node resizex.JS
来源: http://www.bubuko.com/infodetail-3717122.html