api/libs/resize.js

63 lines
1.3 KiB
JavaScript
Raw Normal View History

2018-09-19 21:49:02 +02:00
const fs = require('fs')
const resizeImg = require('resize-img')
class Resize {
constructor (width, heigth) {
this.size = {
width: 128,
heigth: 128
}
if (width && heigth) {
this.setSize(width, heigth)
}
}
_createOutputFilename (input) {
return `${input}_${this.size.width}x${this.size.heigth}`
}
_resize (input, output, callback) {
fs.readFile(input, (err, data) => {
if (err) {
callback(err, null)
return false
}
resizeImg(data, this.size).then(buf => {
fs.writeFile(output, buf, (err) => {
if (err) {
callback(err, null)
return false
}
callback(null, { input: input, output: output, size: this.size })
})
})
})
}
setSize (width, heigth) {
this.size = {
width: width,
heigth: heigth
}
}
createThumbnail (file, callback) {
this.setSize(128, 128)
this._resize(file, this._createOutputFilename(file), callback)
}
createLargeImage (file, callback) {
this.setSize(1600, 1200)
this._resize(file, this._createOutputFilename(file), callback)
}
resize (file, width, heigth, callback) {
this.setSize(width, heigth)
this._resize(file, this._createOutputFilename(file), callback)
}
}
module.exports = Resize