-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresize.js
49 lines (35 loc) · 1.44 KB
/
resize.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
const fs = require("fs");
const sharp = require("sharp");
const axios = require("axios");
const cache = new Map();
function getExtension(filename) {
var i = filename.lastIndexOf('.');
return (i < 0) ? '' : filename.substr(i + 1);
}
module.exports = async function resize(url, width, height, res) {
try {
if (cache.get(url + width + height)) {
const readStream = fs.createReadStream(cache.get(url + width + height));
return readStream.pipe(res);
}
let response = await axios.get(url, { responseType: "arraybuffer" });
let format = getExtension(response.request.path) || "png";
let rnd = Math.random();
let image = "./images/" + rnd + "e." + format;
let buffer = Buffer.from(response.data);
let transform = sharp(buffer);
if (format) transform = transform.toFormat(format);
if (width || height) transform = transform.resize(width, height);
let data = await transform.toBuffer();
res.type(`image/${format}`);
res.set('Cache-control', 'public, max-age=280800');
res.send(data);
cache.set(url + width + height + format, image)
transform.toFile(image).catch((err) => {
resize("https://usercontent.caards.me/pxl.png", format, width, height, res);
});
} catch (err) {
console.log(err)
resize("https://usercontent.caards.me/pxl.png", width, height, res);
}
}