nfp_sites/api/media/resize.mjs

102 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-02-20 16:10:37 +00:00
import sharp from 'sharp'
2019-09-14 19:03:38 +00:00
import Media from './model.mjs'
2019-02-20 16:10:37 +00:00
export default class Resizer {
constructor(opts = {}) {
Object.assign(this, {
Media: opts.Media || Media,
sharp: opts.sharp || sharp,
})
}
2021-01-04 17:47:59 +00:00
createSmall(input, format = 'jpg') {
let output = this.Media.getSubUrl(input, 'small', format === 'avif' ? 'avif' : 'jpg')
2019-02-20 16:10:37 +00:00
2021-01-04 17:47:59 +00:00
let sized = this.sharp(input)
.resize(500, 500, {
fit: sharp.fit.inside,
withoutEnlargement: true,
})
if (format === 'avif') {
return sized
.avif({
quality: 80,
speed: 5,
})
.toFile(output)
.then(() => output)
} else {
return sized
.jpeg({
quality: 93,
})
.toFile(output)
.then(() => output)
}
2019-02-20 16:10:37 +00:00
}
2021-01-04 17:47:59 +00:00
createMedium(input, height, format = 'jpg') {
let output = this.Media.getSubUrl(input, 'medium', format === 'avif' ? 'avif' : 'jpg')
2019-02-20 16:10:37 +00:00
2021-01-04 17:47:59 +00:00
let sized = this.sharp(input)
.resize(800, height || 800, {
fit: height && sharp.fit.cover || sharp.fit.inside,
withoutEnlargement: true,
})
if (format === 'avif') {
return sized
.avif({
quality: 80,
speed: 5,
})
.toFile(output)
.then(() => output)
} else {
return sized
.jpeg({
quality: 93,
})
.toFile(output)
.then(() => output)
}
}
2021-01-04 17:47:59 +00:00
createLarge(input, format = 'jpg') {
let output = this.Media.getSubUrl(input, 'large', format === 'avif' ? 'avif' : 'jpg')
2021-01-04 17:47:59 +00:00
let sized = this.sharp(input)
.resize(1280, 1280, {
fit: sharp.fit.inside,
withoutEnlargement: true,
})
if (format === 'avif') {
return sized
.avif({
quality: 85,
speed: 5,
})
.toFile(output)
.then(() => output)
} else {
return sized
.jpeg({
quality: 93,
})
.toFile(output)
.then(() => output)
}
2019-02-20 16:10:37 +00:00
}
autoRotate(input) {
const output = `${input}_2.jpg`
return this.sharp(input)
.rotate()
.toFile(output)
.then(() => output)
}
}