1、初始化

首先新建一个 tailor-img 文件夹,接着执行 npm init -y 初始化一个package.json

2、安装相关插件

  • archiver 压缩文件
  • canvas 裁剪图片
  • glob 批量获取路径

npm i archiver canvas glob —save

3、app.js

  1. const fs = require('fs')
  2. const { basename } = require('path')
  3. // 压缩文件
  4. const archiver = require('archiver')
  5. // canvas库,用于裁剪图片
  6. const { createCanvas, loadImage } = require('canvas')
  7. // 批量获取路径
  8. const glob = require('glob')
  9. const config = require('./config')
  10. // 根据宽高获取配置
  11. function getOptions(options, config) {
  12. const [sourceWidth, sourceHeight] = options
  13. const { width, height, isWidth, isHeight, scale } = config
  14. const haveWidth = [width, (sourceHeight * width * scale) / sourceWidth]
  15. const haveHeight = [(sourceWidth * height * scale) / sourceHeight, height]
  16. if (width === 0 || height === 0) {
  17. return [0, 0]
  18. }
  19. if (width && height) {
  20. if (isWidth) {
  21. return haveWidth
  22. }
  23. if (isHeight) {
  24. return haveHeight
  25. }
  26. return [width / scale, height / scale]
  27. }
  28. if (width && !height) {
  29. return haveWidth
  30. }
  31. if (height && !width) {
  32. return haveHeight
  33. }
  34. return options.map((item) => item / scale)
  35. }
  36. !(async () => {
  37. const paths = glob.sync('./images/*')
  38. // 压缩成zip
  39. const archive = archiver('zip', {
  40. zlib: {
  41. level: 9,
  42. },
  43. })
  44. // 输出到当前文件夹下的 image-resize.zip
  45. const output = fs.createWriteStream(__dirname + '/image-resize.zip')
  46. archive.pipe(output)
  47. for (let i = 0; i < paths.length; i++) {
  48. const path = paths[i]
  49. const image = await loadImage(path)
  50. const { width, height } = image
  51. // 由于使用了扩展运算符展开对象,这里需要为对象定义迭代器
  52. const obj = { width, height }
  53. obj[Symbol.iterator] = function () {
  54. return {
  55. next: function () {
  56. let objArr = Reflect.ownKeys(obj)
  57. if (this.index < objArr.length - 1) {
  58. let key = objArr[this.index]
  59. this.index++
  60. return { value: obj[key] }
  61. } else {
  62. return { done: true }
  63. }
  64. },
  65. index: 0,
  66. }
  67. }
  68. // 默认缩放2倍
  69. // const options = [width, height].map((item) => item / 2)
  70. const options = getOptions(obj, config)
  71. const canvas = createCanvas(...options)
  72. const ctx = canvas.getContext('2d')
  73. ctx.drawImage(image, 0, 0, ...options)
  74. archive.append(canvas.toBuffer(), { name: `${basename(path)}` })
  75. }
  76. })()

4、config.js 用于修改宽高等配置

  1. module.exports = {
  2. width: 300,
  3. height: '',
  4. // 根据宽度等比缩放,优先级更高
  5. isWidth: true,
  6. // 根据高度等比缩放
  7. isHeight: false,
  8. // 宽高整体缩放
  9. scale: 1,
  10. }