批量压缩图片
Posted jinly
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了批量压缩图片相关的知识,希望对你有一定的参考价值。
var images = require("images"); var fs = require("fs"); var path = "./images"; async function deleteall (path) { var files = []; if(fs.existsSync(path)) { files = fs.readdirSync(path); files.forEach(function(file, index) { var curPath = path + "/" + file; if(fs.statSync(curPath).isDirectory()) { // recurse deleteall(curPath); } else { // delete file fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } }; function explorer(path){ fs.readdir(path, async function(err, files){ if(err){ console.log(‘error: ‘ + err); return; } await deleteall(‘./compressImages‘) fs.mkdir("./compressImages/",function(err){ if (err) { return console.error(err); } files.forEach(function(file){ fs.stat(path + ‘/‘ + file, function(err, stat){ if(err){console.log(err); return;} if(stat.isDirectory()){ explorer(path + ‘/‘ + file); }else{ let name = path + ‘/‘ + file; let outName = ‘./compressImages‘+ ‘/‘ +file let width = images(name).width() if(images(name).width()>750){ images(name) .size(750) .save(outName, { quality : 100 }); } else{ images(name) .save(outName, { quality : 40 }); } } }); }); }); }); } explorer(path);
以上是关于批量压缩图片的主要内容,如果未能解决你的问题,请参考以下文章