4

Node.js——切图

 3 years ago
source link: https://segmentfault.com/a/1190000040436932
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Node.js——切图

我在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.height
console.log(currentImageInfo)

const heights = []
const SPLIT_HEIGHT = 200
while (clientHeight > 0) {
    // 切图高度充足时
    if (clientHeight >= SPLIT_HEIGHT) {
        heights.push(SPLIT_HEIGHT)

        clientHeight -= SPLIT_HEIGHT

    } else {
        // 切割高度不够时,直接切成一张
        heights.push(clientHeight)

        clientHeight = 0
    }
}

console.log(heights)

let top = 0

heights.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

image.png

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 模块机制


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK