关于node.js:Nodejs切图

4次阅读

共计 1977 个字符,预计需要花费 5 分钟才能阅读完成。

我在 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

扩大

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

正文完
 0