-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
93 lines (75 loc) · 2.06 KB
/
app.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
import express from 'express';
import { ImagePool } from '@squoosh/lib';
const port = 1041;
const app = express();
app.use(express.json({ limit: '16mb' }))
// import { cpus } from 'os';
const imagePool = new ImagePool(1); //cpus().length
app.post('/info', async (req, res, next) => {
try {
let b = req.body;
if (b.image == null) {
res.status(400);
res.type('application/json');
return res.end(JSON.stringify({
"error": "image is null"
}))
}
let imageRequest = Buffer.from(b.image, 'base64');
const image = imagePool.ingestImage(imageRequest);
let decoded = await image.decoded;
return res.send(JSON.stringify({
width: decoded.bitmap.width,
height: decoded.bitmap.height
}));
} catch (err) {
res.status(400);
res.type('application/json');
return res.end(JSON.stringify({
"error": err.toString()
}))
}
});
app.post('/', async (req, res, next) => {
try {
let b = req.body;
if (b.image == null) {
res.status(400);
res.type('application/json');
return res.end(JSON.stringify({
"error": "image is null"
}))
}
let imageRequest = Buffer.from(b.image, 'base64');
const image = imagePool.ingestImage(imageRequest);
await image.decoded;
if (b.resize != null) {
await image.preprocess({
resize: b.resize
});
}
if (b.mozjpeg == null) {
res.status(400);
res.type('application/json');
return res.end(JSON.stringify({
"error": "mozjpeg is null"
}))
}
await image.encode({
mozjpeg: b.mozjpeg
});
const rawEncodedImage = (await image.encodedWith.mozjpeg).binary;
let imageResponseBuffer = Buffer.from(rawEncodedImage);
let imageResponse = imageResponseBuffer.toString('base64');
return res.send(imageResponse);
} catch (err) {
res.status(400);
res.type('application/json');
return res.end(JSON.stringify({
"error": err.toString()
}))
}
});
app.listen(port, () =>
console.log(`squoosh-api listening on port ${port}!`),
);