api/libs/resize.js
2019-03-12 23:00:37 +01:00

67 lines
1.5 KiB
JavaScript

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) => {
console.log('après readfile')
if (err) {
callback(err, null)
return false
}
resizeImg(data, this.size)
.then(buf => {
console.log('then rezise')
fs.writeFile(output, buf, (err) => {
console.log('write file')
if (err) {
callback(err, null)
return false
}
callback(null, { input: input, output: output, size: this.size })
})
})
.catch(callback)
})
}
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(1200, 900)
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