-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (38 loc) · 1.21 KB
/
index.js
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
import Canvas from "canvas";
import crop from "crop-universal";
const defaultOptions = {
outputFormat: "png",
};
const cropper = crop(Canvas);
/**
* @typedef {Object} Options
* @prop {String} [outputFormat="png"] - Format of the output image (`"png"` or `"jpeg"`)
*/
/**
* Crop transparent pixels from an image
* @param {String|Canvas.Canvas|Canvas.Image} input - Path to the image to process, another Canvas or an Image
* @param {Options} [options] - Some options
* @returns {Promise<Buffer>}
*/
export default async (input, options = {}) => {
const { outputFormat } = {
...defaultOptions,
...options,
};
const supportedFormat = ["png", "jpeg"];
if (!supportedFormat.includes(outputFormat)) {
const supported = JSON.stringify(supportedFormat);
throw new Error(`outputFormat should only be one of ${supported}, but "${outputFormat}" was given.`);
}
const canvas = await cropper(input, options);
return new Promise((resolve, reject) => {
canvas.toBuffer((error, buffer) => {
if (error) {
reject(error);
}
else {
resolve(buffer);
}
}, `image/${outputFormat}`);
});
};