我在juejin看到一篇文章百万PV商城实际系列 - 前端图片资源优化实战,的影响,通过代码实现切图
装置
# 建一个文件npm init # 装置两个依赖npm i image-size sharp
代码
const sizeOf = require('image-size');const sharp = require('sharp');const currentImageInfo = sizeOf('./wallhaven-3zwvk3.jpg') // 加载一张图let clientHeight = currentImageInfo.heightconsole.log(currentImageInfo)const heights = []const SPLIT_HEIGHT = 200while (clientHeight > 0) { // 切图高度短缺时 if (clientHeight >= SPLIT_HEIGHT) { heights.push(SPLIT_HEIGHT) clientHeight -= SPLIT_HEIGHT } else { // 切割高度不够时,间接切成一张 heights.push(clientHeight) clientHeight = 0 }}console.log(heights)let top = 0heights.forEach((h, index) => { sharp('./wallhaven-3zwvk3.jpg') .extract({ left: 0, top: top, width: currentImageInfo.width, height: h }) .toFile(`./img/split_${index + 1}_block.jpg`, (err, info) => { if(!err){ onsole.log(`split_${index + 1}_block.jpg切割胜利`) }else{ console.log(JSON.stringify(err), 'error') } }) top += h})
执行
node index.js
扩大
sharp
一个利用高速node.js将一般大图片转换成更小的、对web更敌对的JPEG、PNG、WebP等不同尺寸的图像的杰出的模块。
调整图像大小通常比应用最快的ImageMagick和GraphicsMagick设置还要快4到5倍
extract
提取图像的一个区域
- left 从左边缘开始的零索引偏移量
- top zero-indexed offset from top edge
- width 提取图像的宽度
- height 提取图像的高度
toFile
将输入图像数据写入文件。
如果没有抉择输入格局,将从扩大中推断它,反对JPEG、PNG、WebP、TIFF、DZI和libvip的V格局。留神,原始像素数据只反对缓冲区输入。
未提供回调时,将返回Promise
- fileOut (String) 写入图像数据的门路
- callback (Function) 在实现时调用,带有两个参数(err, info)。info蕴含输入图像格式、大小(字节)、宽度、高度、通道和预乘(批示是否应用预乘)。在应用裁剪策略时还蕴含cropOffsetLeft和cropOffsetTop
示列
.toFile(`./img/split_${index + 1}_block.jpg`, (err, info) => { if (!err) { onsole.log(`split_${index + 1}_block.jpg切割胜利`) } else { console.log(JSON.stringify(err), 'error') }}).toFile(`./img/split_${index + 1}_block.jpg`).then(info => { console.log(`split_${index + 1}_block.jpg切割胜利`)}).catch(err => { console.log(JSON.stringify(err), 'error')})
sharp.js中文文档
image-size.js文档
Nodejs中为什么require不能间接引入图片?
const img = require('./wallhaven-3zwvk3.jpg');
用node执行这段代码,会报错,就引发了题目所问
require能加载.js,.json,.node的扩展名,这个node的加载模块机制无关。
我常常写Vue,在Vue中是能够用的,是因为vue应用了webpack,webpack会将辨认require或者import将其转换成本人的webpack模块,比方require转换成__webpack_require__。
然而webpack只能辨认JS,所以webpack有个重要的概念Loader,通过file-loader或者url-loader就能辨认非js的图片文件。
浅谈 Node.js 模块机制