头图
I saw an article in million PV mall practice series-front-end picture resource optimization actual combat , the impact of cutting pictures through code

Install

# 建一个文件
npm init 
# 安装两个依赖
npm i image-size sharp    

Code

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
})

implement

node index.js

image.png

Expand

sharp

An excellent module that uses high-speed node.js to convert ordinary large pictures into smaller, more web-friendly JPEG, PNG, WebP and other images of different sizes.
Resizing images is usually 4 to 5 times faster than using the fastest ImageMagick and GraphicsMagick settings
extract

Extract an area of the image

  • left zero index offset from the left edge
  • top zero-indexed offset from top edge
  • width extract the width of the image
  • height Extract the height of the image

toFile

Write the output image data to the file.

If the output format is not selected, it will be inferred from the extension, supporting JPEG, PNG, WebP, TIFF, DZI, and libvip's V format. Note that the original pixel data only supports buffer output.

When no callback is provided, Promise will be returned

  • fileOut (String) The path to write image data
  • callback (Function) is called upon completion, with two parameters (err, info). info contains the output image format, size (bytes), width, height, channel and pre-multiplication (indicating whether to use pre-multiplication). When using the cropping strategy, cropOffsetLeft and cropOffsetTop are also included
Show
.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 Chinese document

image-size.js document

Why can't require directly import images in Nodejs?

const img = require('./wallhaven-3zwvk3.jpg');

If you execute this code with node, an error will be reported, which will cause the title to ask

Require can load the extensions of .js, .json, and .node, which is related to the module loading mechanism of node.

I often write Vue, and it can be used in Vue because Vue uses webpack. Webpack will recognize require or import and convert it into its own webpack module, for example, convert require to __webpack_require__.

But webpack can only recognize JS, so webpack has an important concept Loader, which can recognize non-js image files through file-loader or url-loader.

Talking about the Node.js module mechanism


羊先生
1.9k 声望821 粉丝