imagemin图片压缩

前言:清明三天假期已过手机上存储了不少的游玩照片,由于图片资源比较大在发送给朋友的时候特别慢。所以临时起义决定使用nodeJS进行处理一下。

imageminnpm官网介绍: https://www.npmjs.com/package/imagemin
建议更改为淘宝镜像,使用cnpm install imageminnpm进行模块的安装。

一、压缩效果对照

对照改图imageminnpm支持有损和无损压缩,同时支持不同类型的图片资源。
在这里插入图片描述
针对png和jpg两种类型的图片进行压缩,对比效果看一下:压前后大小减少了60%,图片效果没有任何变化。
在这里插入图片描述
在这里插入图片描述

二、代码展示:

在原始图片文件佳平级路径下生成一个新的同结构的文件夹
比如:愿资源文件夹:xx; 压缩后生成的文件夹:xx_new(压缩前后文件夹中的结构和图片的名称是没有变化的)

import imagemin from 'imagemin';
import imageminMozjpeg from 'imagemin-Mozjpeg';
import imageminPngquant from 'imagemin-pngquant';

import * as fs from 'fs';
import * as path from 'path';

function getFileDirectory(_pathName) {
	let fileData = fs.readdirSync(_pathName);
	if (fileData) {
		for (let i = 0, j = fileData.length; i < j; i++) {
			let tempPath = path.join(_pathName, fileData[i]);
			let fileState = fs.statSync(tempPath);
			if (fileState.isDirectory()) {
				sourPathArray.push(tempPath);
				getFileDirectory(tempPath);
			}
		}
	}
}

//路径下获取对应得文件夹路径
let sourPathArray = [];
let sourcePath = process.argv[2];
let rootId = 0;
if (fs.statSync(sourcePath).isDirectory()) {
	sourPathArray.push(sourcePath);
	getFileDirectory(sourcePath);

	//获取路径目录index
	let tempArray = sourcePath.split(path.sep);
	rootId = tempArray.length - 1;
}
else {
	console.log('缺少路径参数或非法路径!');
}


//按照存储路径结构生成对应得文件夹
let newName = '_new';
let desPathArray = [];
for (let i = 0, j = sourPathArray.length; i < j; i++) {
	let tepmArray = sourPathArray[i].split(path.sep);
	tepmArray[rootId] = tepmArray[rootId] + newName;

	let destPath = tepmArray.join(path.sep);
	fs.mkdirSync(destPath, { recursive: true });
	desPathArray.push(destPath);
}

//压缩图片
sourPathArray.forEach(async (value, index) => {
	const files = await imagemin([path.join(value, '*.{jpg,png}')], {
		destination: desPathArray[index],
		plugins: [
			imageminMozjpeg(),
			imageminPngquant()
		]
	});
	console.log(files);
})

三、使用展示:

注意:1、最好使用cnpm进行安装,可避免一些安装失败的问题。
2、建议使用npm init生成package,并添加: “type”: “module”,来减少在使用中的一些报错。如果遇到什么问题可以百度进行查看解决~
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值