This repository has been archived by the owner on Feb 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageUtils.js
71 lines (63 loc) · 1.89 KB
/
imageUtils.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
const debug = require("debug")("StaticMaps-gl.imageUtils");
const sharp = require("sharp");
debug("simd available: " + sharp.simd(true));
exports.parseImageFormat = function(format) {
var imageFormat;
var mimetype;
var imageOptions = {};
if (format.startsWith("png")) {
mimetype = "image/png";
imageFormat = "png";
} else if (format.startsWith("jpeg") || format.startsWith("jpg")) {
mimetype = "image/jpeg";
imageFormat = "jpeg";
} else if (format.startsWith("webp")) {
mimetype = "image/webp";
imageFormat = "webp";
} else {
return undefined;
}
if (imageFormat == "jpeg" || imageFormat == "webp") {
if (format.endsWith("70")) {
imageOptions["quality"] = 70;
} else if (format.endsWith("80")) {
imageOptions["quality"] = 80;
} else if (format.endsWith("90")) {
imageOptions["quality"] = 90;
} else if (format.endsWith("100")) {
imageOptions["quality"] = 100;
}
} else if (imageFormat == "png") {
imageOptions["adaptiveFiltering"] = false;
imageOptions["progressive"] = false;
imageOptions["compressionLevel"] = 9;
}
return {
format: imageFormat,
mimetype,
options: imageOptions
};
};
exports.sendImageResponse = function(res, width, height, data, imageFormat) {
const start = Date.now();
const image = sharp(data, {
raw: {
width: width,
height: height,
channels: 4
}
});
var formattedImage;
if (imageFormat.format == "png") {
formattedImage = image.png(imageFormat.options);
} else if (imageFormat.format == "jpeg") {
formattedImage = image.jpeg(imageFormat.options);
} else if (imageFormat.format == "webp") {
formattedImage = image.webp(imageFormat.options);
}
formattedImage.toBuffer(function(err, data, info) {
debug("Saving image complete in " + (Date.now() - start) + "ms");
res.type(imageFormat.mimetype);
res.send(data);
});
};