Zmiana rozmiaru i konwersja obrazów
Total.js przetwarza obrazy, wywołując GraphicsMagick (gm) lub ImageMagick, które muszą być zainstalowane na serwerze (brew install graphicsmagick, apt install graphicsmagick). Ustawienie $imageconverter wybiera program: gm (domyślnie), im lub magick.
Image.load(filename) (albo Buffer lub strumień) zwraca łańcuch, który zapisuje operacje i wykonuje je po wywołaniu .save(filename, callback). Przydatne operacje to resize(width, height) (zachowuje proporcje w ramce), thumbnail(width, height) (szybki, mały podgląd), miniature(width, height) (mieści obraz w ramce, a resztę wypełnia tłem), crop(width, height, x, y), rotate(degrees), grayscale(), blur(radius), quality(percentage) oraz output('jpg') do zmiany formatu. Przesłane pliki robią to bezpośrednio: file.image() w handlerze tras @upload zwraca ten sam łańcuch.
Odczyt rozmiaru nie wymaga GraphicsMagick: Image.measure('png', buffer) zwraca { width, height } z pierwszych bajtów danych PNG, JPG, GIF i WebP.
$.image(options) służy do trasy, która tworzy obraz na żądanie: ext to format, load(next) przekazuje źródło (strumień lub ścieżkę) przez next(...), image(img) opisuje operacje, a cache to nazwa, pod którą wynik jest przechowywany w tmp/ dla kolejnych żądań.
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);
}
});
}