Ridimensionare e convertire immagini
Total.js elabora le immagini chiamando GraphicsMagick (gm) o ImageMagick, che devono essere installati sul server (brew install graphicsmagick, apt install graphicsmagick). L'impostazione $imageconverter sceglie il programma: gm (predefinito), im o magick.
Image.load(filename) (o un Buffer o uno stream) restituisce una catena che registra le operazioni e le esegue quando chiami .save(filename, callback). Le operazioni utili sono resize(width, height) (mantiene le proporzioni dentro il riquadro), thumbnail(width, height) (una piccola anteprima veloce), miniature(width, height) (adatta l'immagine al riquadro e riempie il resto con lo sfondo), crop(width, height, x, y), rotate(degrees), grayscale(), blur(radius), quality(percentage) e output('jpg') per convertire il formato. Con i file caricati si fa direttamente: file.image() in un gestore di rotte @upload restituisce la stessa catena.
Leggere le dimensioni non richiede GraphicsMagick: Image.measure('png', buffer) restituisce { width, height } dai primi byte di dati PNG, JPG, GIF e WebP.
$.image(options) serve per una rotta che crea un'immagine su richiesta: ext è il formato, load(next) consegna la sorgente (uno stream o un percorso) con next(...), image(img) descrive le operazioni e cache è il nome con cui il risultato viene conservato in tmp/ per le richieste successive.
const Zlib = require('zlib');
const Fs = require('fs');
exports.install = function() {
ROUTE('GET /resize/', resize);
ROUTE('GET /thumb/', thumb);
};
// Builds a solid red PNG so that the example needs no file
function makepng(width, height) {
function chunk(type, data) {
var length = Buffer.alloc(4);
length.writeUInt32BE(data.length);
var body = Buffer.concat([Buffer.from(type), data]);
var crc = Buffer.alloc(4);
crc.writeUInt32BE(Zlib.crc32(body));
return Buffer.concat([length, body, crc]);
}
var header = Buffer.alloc(13);
header.writeUInt32BE(width, 0);
header.writeUInt32BE(height, 4);
header[8] = 8; // bit depth
header[9] = 2; // RGB
var row = Buffer.alloc(1 + width * 3);
for (var x = 0; x < width; x++)
row[1 + x * 3] = 255;
var raw = Buffer.concat(Array(height).fill(row));
return Buffer.concat([
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
chunk('IHDR', header),
chunk('IDAT', Zlib.deflateSync(raw)),
chunk('IEND', Buffer.alloc(0))
]);
}
function source() {
var filename = PATH.tmp('source.png');
Fs.writeFileSync(filename, makepng(200, 100));
return filename;
}
function resize($) {
var target = PATH.tmp('small.jpg');
Image.load(source()).resize(50, 50).output('jpg').save(target, function(err) {
if (err) {
$.invalid(err);
return;
}
var size = Image.measure('jpg', Fs.readFileSync(target));
$.json({ width: size.width, height: size.height, original: Image.measure('png', Fs.readFileSync(source())) });
});
}
function thumb($) {
$.image({
ext: 'png',
cache: 'thumb-example',
load: function(next) {
next(Fs.createReadStream(source()));
},
image: function(img) {
img.resize(40, 40);
}
});
}