const
fs =
require
(
'fs'
)
const
{
basename
} =
require
(
'path'
)
const
archiver =
require
(
'archiver'
)
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/*'
)
const
archive = archiver(
'zip'
, {
zlib: {
level: 9,
},
})
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,
}
}
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)}` })
}
})()