File size: 1,666 Bytes
c015809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import sharp from 'sharp';
import smartcrop from './smartcrop.js';

// disable SIMD for avoid sharp crash
sharp.simd(false);

export function rgb2rgba(input) {
	var output = Buffer.alloc((input.length / 3) * 4);
	for (var i = 0; i < input.length; i += 3) {
		output[(i / 3) * 4] = input[i];
		output[(i / 3) * 4 + 1] = input[i + 1];
		output[(i / 3) * 4 + 2] = input[i + 2];
		output[(i / 3) * 4 + 3] = 255;
	}
	return output;
}

export var iop = {
	open: function (src) {
		var image = sharp(src);
		return image.metadata().then(function (metadata) {
			return {
				width: metadata.width,
				height: metadata.height,
				_sharp: image,
			};
		});
	},
	resample: function (image, width, height) {
		// this does not clone the image, better performance but fragile
		// (depends on the assumtion that resample+getData is only called once per img)
		return new Promise(function (resolve) {
			resolve({
				width: ~~width,
				height: ~~height,
				_sharp: image._sharp,
			});
		});
	},
	getData: function (image) {
		var options = { kernel: sharp.kernel.cubic };
		return image._sharp
			.resize(image.width, image.height, options)
			.raw()
			.toBuffer()
			.then(function (data) {
				if (data.length === image.width * image.height * 3) {
					data = rgb2rgba(data);
				}
				if (data.length !== image.width * image.height * 4) {
					throw new Error('unexpected data length ' + data.length);
				}

				return new smartcrop.ImgData(image.width, image.height, data);
			});
	},
};

export function crop(img, options, callback) {
	options = options || {};
	options.imageOperations = iop;
	return smartcrop.crop(img, options, callback);
}

export default crop;