server/services/cover/resizer.js
Artem Anufrij cff48aaada
All checks were successful
continuous-integration/drone Build is passing
move
2023-02-08 12:30:56 +01:00

97 lines
2.4 KiB
JavaScript

const sharp = require("sharp");
const fs = require("fs");
/*
RADIO COVER
*/
const radio_cover_sizes = [
{ width: 128, height: 128, fit: "cover" },
{ width: 64, height: 64, fit: "cover" },
{ width: 32, height: 32, fit: "cover" }
];
exports.resize_image_for_radio = function (image, callback) {
resizer(image, radio_cover_sizes, callback);
};
/*
ALBUM COVER
*/
const album_cover_sizes = [
{ width: 256, height: 256, fit: "cover" },
{ width: 128, height: 128, fit: "cover" },
{ width: 64, height: 64, fit: "cover" },
{ width: 32, height: 32, fit: "cover" }
];
exports.resize_image_for_album = function (image, callback) {
if (typeof image === 'string') {
let data = fs.readFileSync(image);
resizer(data, album_cover_sizes, callback);
} else {
resizer(image, album_cover_sizes, callback);
}
};
/*
ARTIST COVER
*/
const artist_cover_sizes = [
{ width: 1024, height: 512, fit: "cover" },
{ width: 512, height: 256, fit: "cover" },
{ width: 256, height: 128, fit: "cover" },
{ width: 128, height: 64, fit: "cover" },
{ width: 64, height: 32, fit: "cover" }
];
exports.resize_image_for_artist = function (image, callback) {
if (typeof image === 'string') {
console.log("resizing: " + image);
let data = fs.readFileSync(image);
resizer(data, artist_cover_sizes, callback);
} else {
resizer(image, artist_cover_sizes, callback);
}
};
/*
BOX COVER
*/
const box_cover_sizes = [
{ width: 256, height: 362, fit: "cover" },
{ width: 128, height: 181, fit: "cover" },
{ width: 64, height: 90, fit: "cover" },
{ width: 32, height: 45, fit: "cover" }
];
exports.resize_image_for_box = function (image, callback) {
if (typeof image === 'string') {
let data = fs.readFileSync(image);
resizer(data, box_cover_sizes, callback);
} else {
resizer(image, box_cover_sizes, callback);
}
};
function resizer(image, array, callback) {
let result = {}
let runner = (image, index) => {
if (index < array.length) {
let size = array[index];
sharp(image)
.resize(size)
.png()
.toBuffer()
.then(data => {
result["cover" + size.width] = "data:image/png;base64, " + Buffer.from(data).toString("base64");
runner(data, ++index);
}).catch(err=>{
console.log(err);
});
} else {
if (callback) {
callback(result);
}
}
}
runner(image, 0);
}