-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.js
103 lines (85 loc) · 3.17 KB
/
api.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/* jshint
esversion: 6,
node: true
*/
(() => {
"use strict";
var jimp = require("jimp");
var express = require("express");
var router = express.Router();
var imagePath = `${__dirname}/lemonysnicket.jpg`;
var xPadding = 10;
var cleanImage;
var captionFont;
var imageLoaded = jimp.read(imagePath).then((image) => {
cleanImage = image;
});
var fontLoaded = jimp.loadFont(jimp.FONT_SANS_32_WHITE).then((font) => {
captionFont = font;
});
// This function is copied from the Jimp implmentation
// (https://github.com/oliver-moran/jimp/blob/master/index.js#L2381)
// License: https://github.com/oliver-moran/jimp/blob/master/LICENSE
// Once https://github.com/oliver-moran/jimp/pull/199 has been merged, this can be removed
function measureText(font, text) {
var x = 0;
for (var i = 0; i < text.length; i++) {
if (font.chars[text[i]]) {
x += font.chars[text[i]].xoffset
+ (font.kernings[text[i]] && font.kernings[text[i]][text[i+1]] ? font.kernings[text[i]][text[i+1]] : 0)
+ (font.chars[text[i]].xadvance || 0);
}
}
return x;
}
function getLinesOfText(font, text, maxWidth) {
var words = text.split(" ");
var lines = [];
var line = "";
words.forEach((word) => {
if (measureText(font, `${line} ${word}`) > maxWidth) {
lines.push(line);
line = word;
} else {
line = `${line} ${word}`;
}
});
lines.push(line);
return lines;
}
function writeTextToImage(image, font, text, maxWidth) {
var lineHeight = font.common.lineHeight;
var yPadding = 1.5 * lineHeight;
var y = image.bitmap.height - yPadding - lineHeight;
var lines = getLinesOfText(font, text, maxWidth);
// print all lines starting with the last one so we know where the others are placed on the y-axis
lines.reverse();
lines.forEach((line) => {
var x = (image.bitmap.width / 2) - (measureText(font, line) / 2) + xPadding;
image.print(font, x, y, line);
y -= lineHeight;
});
return image;
}
router.get("/:text64", (req, res) => {
var text = (req.params.text64 ? new Buffer(req.params.text64, "base64").toString() : "");
res.contentType("image/jpeg");
Promise.all([imageLoaded, fontLoaded]).then(() => {
var image = new jimp(cleanImage);
var width = image.bitmap.width - (2 * xPadding);
image = writeTextToImage(image, captionFont, text, width);
image.getBuffer(jimp.AUTO, (error, buffer) => {
if (!error) {
res.end(buffer);
} else {
console.error(`Error: ${error}`);
res.end();
}
});
})
.catch((error) => {
console.error(error);
});
});
module.exports = router;
})();