图片压缩小工具

使用tinypng进行图片压缩:

使用nodejs执行即可

const fs = require('fs');
const path = require('path');
const https = require('https');
const crypto = require('crypto');
const {
	URL
} = require('url');

const root = './image/',
	exts = ['.jpg', '.png','jpeg'],
	max = 5200000; // 5MB == 5242848.754299136

const options = {
	method: 'POST',
	hostname: 'tinypng.com',
	path: '/web/shrink',
	headers: {
		rejectUnauthorized: false,
		'Postman-Token': Date.now(),
		'Cache-Control': 'no-cache',
		'Content-Type': 'application/x-www-form-urlencoded',
		'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
	}
};

fileList(root);

// 获取文件列表
function fileList(folder) {
	fs.readdir(folder, (err, files) => {
		if (err) console.error(err);
		files.forEach(file => {
			fileFilter(folder + file);
		});
	});
}

// 过滤文件格式,返回所有jpg,png图片
function fileFilter(file) {
	fs.stat(file, (err, stats) => {
		if (err) return console.error(err);
		if (
			// 必须是文件,小于5MB,后缀 jpg||png
			stats.size <= max &&
			stats.isFile() &&
			exts.includes(path.extname(file))
		) {
			fileUpload(file); // console.log('可以压缩:' + file);
		}
		if (stats.isDirectory()) fileList(file + '/');
	});
}
// 异步API,压缩图片
// {"error":"Bad request","message":"Request is invalid"}
// {"input": { "size": 887, "type": "image/png" },"output": { "size": 785, "type": "image/png", "width": 81, "height": 81, "ratio": 0.885, "url": "https://tinypng.com/web/output/7aztz90nq5p9545zch8gjzqg5ubdatd6" }}
function fileUpload(img) {
	var req = https.request(options, function(res) {
		res.on('data', buf => {
			let obj = JSON.parse(buf.toString());
			if (obj.error) {
				console.log(`[${img}]:压缩失败!报错:${obj.message}`);
			} else {
				fileUpdate(img, obj);
			}
		});
	});

	req.write(fs.readFileSync(img), 'binary');
	req.on('error', e => {
		console.error(e);
	});
	req.end();
}
// 该方法被循环调用,请求图片数据
function fileUpdate(imgpath, obj) {
	let options = new URL(obj.output.url);
	let req = https.request(options, res => {
		let body = '';
		res.setEncoding('binary');
		res.on('data', function(data) {
			body += data;
		});

		res.on('end', function() {
			fs.writeFile(imgpath, body, 'binary', err => {
				if (err) return console.error(err);
				console.log(
					`[${imgpath}] \n 压缩成功,原始大小-${obj.input.size},压缩大小-${
            obj.output.size
          },优化比例-${obj.output.ratio}`
				);
			});
		});
	});
	req.on('error', e => {
		console.error(e);
	});
	req.end();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

幻蝶Love

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值