我正在尝试使用NodeJS自动化计算机上的一些琐碎过程。现在,我能够将一些png文件转换为jpg。我想将它们全部打包成拉链。
const fs = require('fs')
const path = require('path')
const jimp = require('jimp')
const files = fs.readdirSync('./')
// Convert all png to jpg
const pngs = files.filter(file => path.extname(file).toLowerCase() === '.png')
let jpgs = []
Promise.all(pngs.map(png => jimp.read('./' + png))).then(jimps => {
jimps.map((img, i) => {
img
.rgba(false)
.background(0xffffffff)
.write(`./jpgs/${path.basename(pngs[i], '.png')}.jpg`)
})
console.log('Done converting')
})
// Zip all the .png and .jpg files into PNGs.zip and JPGs.zip
// TODO:
我摆弄了JSZip,但无法正常工作。
const fs = require('fs')
const path = require('path')
const jimp = require('jimp')
const CLIProgress = require('cli-progress')
const zipPNG = new require('node-zip')()
const zipJPG = new require('node-zip')()
const files = fs.readdirSync('./')
// Convert all png to jpg
const pngs = files.filter(file => path.extname(file).toLowerCase() === '.png')
let jpgs = []
Promise.all(pngs.map(png => jimp.read('./' + png))).then(jimps => {
const bar = new CLIProgress.Bar({}, CLIProgress.Presets.shades_classic)
bar.start(pngs.length, 0)
jimps.map((img, i) => {
img
.rgba(false)
.background(0xffffffff)
.write(`./jpgs/${path.basename(pngs[i], '.png')}.jpg`)
bar.update(i + 1)
})
bar.stop()
console.log('Done converting')
// Pack the files nicely in ZIP
pngs.forEach(png => {
zipPNG.file(png, fs.readFileSync(path.join('./', png)))
zipJPG.file(
`${path.basename(png, '.png')}.jpg`,
fs.readFileSync(`./jpgs/${path.basename(png, '.png')}.jpg`)
)
})
let data = zipPNG.generate({ base64: false, compression: 'DEFLATE' })
fs.writeFileSync('PNG.zip', data, 'binary')
console.log('PNGs zipped')
data = zipJPG.generate({ base64: false, compression: 'DEFLATE' })
fs.writeFileSync('./jpgs/JPG.zip', data, 'binary')
console.log('JPGs zipped')
})