forked from node-gfx/node-canvas-webp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
35 lines (29 loc) · 986 Bytes
/
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
const canvasModule = require("canvas");
const webp = require("./build/Release/canvaswebp.node").canvasToBufferWebp;
// 1.x : 2.x
const Canvas = typeof canvasModule === "function" ? canvasModule : canvasModule.Canvas;
const oToBuffer = Canvas.prototype.toBuffer;
Canvas.prototype.toBuffer = function (format, config, callback) {
if (format === "image/webp") {
config = config || {};
let quality = typeof config.quality === "number" ? config.quality * 100 : 90;
quality = Math.min(quality, 100);
quality = Math.max(quality, 0);
const lossless = typeof config.lossless === "boolean" ? config.lossless : true;
let error = null, encoded;
try {
encoded = webp(this, quality, lossless);
} catch (ex) {
error = ex;
}
if (typeof callback === "function") {
// pseudo-async
process.nextTick(() => callback(error, encoded));
} else {
if (error) throw error;
return encoded;
}
} else {
return oToBuffer.call(this, format, config, callback);
}
};