-
Notifications
You must be signed in to change notification settings - Fork 4
/
meme-creator.js
75 lines (72 loc) · 2.24 KB
/
meme-creator.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
var Jimp = require("jimp");
var path = require("path");
module.exports = function (options, callback) {
try {
let url = options.imageURL;
let directory = "directory" in options ? options.directory : "./";
let fileName = "fileName" in options ? options.fileName : "random";
Jimp.read(url, (err, image) => {
if (err)
return callback({
status: 400,
error: "Invalid image URL",
});
const fileTypes = ["png", "jpg", "jpeg"];
if (!fileTypes.includes(image.getExtension())) {
return callback({
status: 400,
error: `Invalid image type, gif's are not allowed.`,
});
}
if (image.bitmap.height < 100 || image.bitmap.width < 100) {
image.scale(10);
}
const TOP_POS = 5;
const BOTTOM_POS = image.bitmap.height - 45;
Jimp.loadFont(path.join(__dirname, "/impact.fnt")).then((font) => {
image.print(
font,
0,
TOP_POS,
{
text: options.topText.toUpperCase(),
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
},
image.bitmap.width,
image.bitmap.height
);
image.print(
font,
0,
BOTTOM_POS,
{
text: options.bottomText.toUpperCase(),
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
},
image.bitmap.width,
image.bitmap.height
);
if (fileName == "random") {
let randNum = Math.floor(Math.random() * 1000000000 + 1);
image.write(`${directory}meme_${randNum}.` + image.getExtension());
return callback({
status: 200,
fileName: `${directory}meme_${randNum}.` + image.getExtension(),
});
} else {
image.write(`${directory}${fileName}.` + image.getExtension());
return callback({
status: 200,
fileName: `${directory}${fileName}.` + image.getExtension(),
});
}
});
});
} catch (error) {
console.error(error);
return callback({
status: 400,
error: "Something went wrong while creating image: " + error,
});
}
};