首頁  >  文章  >  web前端  >  nodejs怎麼實作對圖片進行批次裁切?

nodejs怎麼實作對圖片進行批次裁切?

青灯夜游
青灯夜游轉載
2020-12-09 17:51:163454瀏覽

nodejs怎麼實作對圖片進行批次裁切?以下這篇文章為大家介紹一下nodejs實作批次裁切圖片功能的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

nodejs怎麼實作對圖片進行批次裁切?

相關推薦:《nodejs 教學

1、初始化

首先新建一個tailor-img 文件夾,接著執行npm init -y 初始化一個package.json

2、安裝相關外掛程式

  • archiver  壓縮檔案
  • canvas  裁切圖片
  • glob  批次取得路徑
npm i  archiver canvas glob --save

3、app.js

const fs = require('fs')
const { basename } = require('path')
// 压缩文件
const archiver = require('archiver')
// canvas库,用于裁剪图片
const { createCanvas, loadImage } = require('canvas')
// 批量获取路径
const glob = require('glob')
const config = require('./config')

// 根据宽高获取配置
function getOptions(options, config) {
  const [sourceWidth, sourceHeight] = options
  const { width, height, isWidth, isHeight, scale } = config
  const haveWidth = [width, (sourceHeight * width * scale) / sourceWidth]
  const haveHeight = [(sourceWidth * height * scale) / sourceHeight, height]
  if (width === 0 || height === 0) {
    return [0, 0]
  }
  if (width && height) {
    if (isWidth) {
      return haveWidth
    }
    if (isHeight) {
      return haveHeight
    }
    return [width / scale, height / scale]
  }
  if (width && !height) {
    return haveWidth
  }
  if (height && !width) {
    return haveHeight
  }
  return options.map((item) => item / scale)
}

!(async () => {
  const paths = glob.sync('./images/*')
  // 压缩成zip
  const archive = archiver('zip', {
    zlib: {
      level: 9,
    },
  })
  // 输出到当前文件夹下的 image-resize.zip
  const output = fs.createWriteStream(__dirname + '/image-resize.zip')
  archive.pipe(output)
  for (let i = 0; i d9bac1fba7d4bff47065a213971afddf item / 2)
    const options = getOptions(obj, config)
    const canvas = createCanvas(...options)
    const ctx = canvas.getContext('2d')
    ctx.drawImage(image, 0, 0, ...options)
    archive.append(canvas.toBuffer(), { name: `${basename(path)}` })
  }
})()

4、config.js用於修改寬高等設定

module.exports = {
  width: 300,
  height: '',
  // 根据宽度等比缩放,优先级更高
  isWidth: true,
  // 根据高度等比缩放
  isHeight: false,
  // 宽高整体缩放
  scale: 1,
}

更多程式相關知識,請造訪:程式設計影片課程! !

以上是nodejs怎麼實作對圖片進行批次裁切?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除