首页 > Web开发 > 详细

nodejs 批量图片瘦身,重设尺寸和图片质量并保存到指定目录

时间:2021-01-17 21:46:50      阅读:61      评论:0      收藏:0      [点我收藏+]

源代码(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

nodejs 批量图片瘦身,重设尺寸和图片质量并保存到指定目录

原文:https://www.cnblogs.com/sochishun/p/14289819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!