nodejs에서 이미지를 일괄적으로 자르는 방법은 무엇입니까?

青灯夜游
풀어 주다: 2020-12-09 17:51:16
앞으로
3495명이 탐색했습니다.

nodejs이미지를 일괄적으로 자르는 방법은 무엇입니까? 다음 기사에서는 nodejs에서 이미지 일괄 자르기를 구현하는 방법을 소개합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

nodejs에서 이미지를 일괄적으로 자르는 방법은 무엇입니까?

관련 권장 사항: "nodejs tutorial"

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 < paths.length; i++) {
    const path = paths[i]
    const image = await loadImage(path)
    const { width, height } = image

    // 由于使用了扩展运算符展开对象,这里需要为对象定义迭代器
    const obj = { width, height }
    obj[Symbol.iterator] = function () {
      return {
        next: function () {
          let objArr = Reflect.ownKeys(obj)
          if (this.index < objArr.length - 1) {
            let key = objArr[this.index]
            this.index++
            return { value: obj[key] }
          } else {
            return { done: true }
          }
        },
        index: 0,
      }
    }
    // 默认缩放2倍
    // const options = [width, height].map((item) => item / 2)
    const options = getOptions(obj, config)
    const canvas = createCanvas(...options)
    const ctx = canvas.getContext(&#39;2d&#39;)
    ctx.drawImage(image, 0, 0, ...options)
    archive.append(canvas.toBuffer(), { name: `${basename(path)}` })
  }
})()
로그인 후 복사

4, config.js는 너비 및 높이와 같은 구성을 수정하는 데 사용됩니다

module.exports = {
  width: 300,
  height: &#39;&#39;,
  // 根据宽度等比缩放,优先级更高
  isWidth: true,
  // 根据高度等比缩放
  isHeight: false,
  // 宽高整体缩放
  scale: 1,
}
로그인 후 복사

자세한 내용은 프로그래밍 관련 지식은 프로그래밍 비디오 코스를 방문하세요! !

위 내용은 nodejs에서 이미지를 일괄적으로 자르는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:segmentfault.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!