Redimensionar e converter imagens
O Total.js processa imagens chamando o GraphicsMagick (gm) ou o ImageMagick, que têm de estar instalados no servidor (brew install graphicsmagick, apt install graphicsmagick). A definição $imageconverter escolhe o programa: gm (por omissão), im ou magick.
Image.load(filename) (ou um Buffer ou um stream) devolve uma cadeia que regista as operações e as executa quando chama .save(filename, callback). As operações úteis são resize(width, height) (mantém as proporções dentro da caixa), thumbnail(width, height) (uma pré-visualização pequena e rápida), miniature(width, height) (ajusta a imagem à caixa e preenche o resto com o fundo), crop(width, height, x, y), rotate(degrees), grayscale(), blur(radius), quality(percentage) e output('jpg') para converter o formato. Com ficheiros carregados faz-se diretamente: file.image() num handler de rotas @upload devolve a mesma cadeia.
Ler o tamanho não precisa do GraphicsMagick: Image.measure('png', buffer) devolve { width, height } a partir dos primeiros bytes de dados PNG, JPG, GIF e WebP.
$.image(options) serve para uma rota que cria uma imagem a pedido: ext é o formato, load(next) entrega a origem (um stream ou um caminho) com next(...), image(img) descreve as operações e cache é o nome sob o qual o resultado fica guardado em tmp/ para os pedidos seguintes.
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);
}
});
}