# Redimensiona y convierte imágenes

> Procesa imágenes con Image.load(), encadena operaciones de redimensionado, recorte y formato, guarda el resultado, mide su tamaño y sirve miniaturas con $.image().

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: es
Content-SHA256: 9aa93b28842afa54cb3d79f717dbc8ff7314107f515a71452f8db1ccd8dc9a09
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

Total.js procesa las imágenes llamando a **GraphicsMagick** (`gm`) o a ImageMagick, que deben estar instalados en el servidor (`brew install graphicsmagick`, `apt install graphicsmagick`). La opción `$imageconverter` elige el programa: `gm` (por defecto), `im` o `magick`.

`Image.load(filename)` (o un `Buffer` o un stream) devuelve una cadena que registra las operaciones y las ejecuta cuando llamas a `.save(filename, callback)`. Las operaciones más útiles son `resize(width, height)` (mantiene las proporciones dentro del cuadro), `thumbnail(width, height)` (una vista previa pequeña y rápida), `miniature(width, height)` (ajusta la imagen al cuadro y rellena el resto con el fondo), `crop(width, height, x, y)`, `rotate(degrees)`, `grayscale()`, `blur(radius)`, `quality(percentage)` y `output('jpg')` para convertir el formato. Con los archivos subidos se hace directamente: `file.image()` en el manejador de rutas `@upload` devuelve la misma cadena.

Leer el tamaño no necesita GraphicsMagick: `Image.measure('png', buffer)` devuelve `{ width, height }` a partir de los primeros bytes de datos PNG, JPG, GIF y WebP.

`$.image(options)` sirve para una ruta que crea una imagen bajo demanda: `ext` es el formato, `load(next)` entrega el origen (un stream o una ruta) con `next(...)`, `image(img)` describe las operaciones y `cache` es el nombre con el que el resultado se guarda en `tmp/` para las siguientes peticiones.

```js controllers/images.js
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);
		}
	});
}
```
