-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
201 lines (163 loc) · 6.4 KB
/
Copy pathserver.js
File metadata and controls
201 lines (163 loc) · 6.4 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import express from "express";
import multer from "multer";
import { createCanvas, loadImage } from "canvas";
import { ditherImage, replaceColors, aitjcizeSpectra6Palette } from "epdoptimize";
const app = express();
app.use(express.json({ limit: "25mb" })); // JSON bodies (imageUrl mode)
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 25 * 1024 * 1024 }, // 25MB
});
// Healthcheck
app.get("/health", (_req, res) => res.json({ ok: true }));
// Helper: parse numbers safely (multipart fields come as strings)
const num = (v, fallback) => {
if (v === undefined || v === null || v === "") return fallback;
const n = Number(v);
return Number.isFinite(n) ? n : fallback;
};
app.post("/optimize", upload.single("image"), async (req, res) => {
// Help functions for image optimization
function clamp255(v) { return v < 0 ? 0 : (v > 255 ? 255 : v); }
// Lift only in dark areas, with a gentle ramp
function liftShadowsSoft(imageData, lift = 10, threshold = 90) {
const d = imageData.data;
for (let i = 0; i < d.length; i += 4) {
const r = d[i], g = d[i+1], b = d[i+2];
const y = 0.2126*r + 0.7152*g + 0.0722*b;
if (y >= threshold) continue;
// Ramp: the darker, the more lift
const t = 1 - (y / threshold); // 0..1
const amt = lift * (t * t); // softer (square)
d[i] = clamp255(Math.round(r + amt));
d[i+1] = clamp255(Math.round(g + amt));
d[i+2] = clamp255(Math.round(b + amt));
}
}
// Gamma on luma (gamma < 1 => brighter)
function applyGammaOnLuma(imageData, gamma = 0.85) {
const d = imageData.data;
const lut = new Uint8ClampedArray(256);
for (let i = 0; i < 256; i++) {
const x = i / 255;
lut[i] = Math.round(Math.pow(x, gamma) * 255);
}
for (let i = 0; i < d.length; i += 4) {
const r = d[i], g = d[i+1], b = d[i+2];
const y0 = Math.round(0.2126*r + 0.7152*g + 0.0722*b);
const y1 = lut[y0];
if (y0 === 0) continue;
const s = y1 / y0;
d[i] = clamp255(Math.round(r * s));
d[i+1] = clamp255(Math.round(g * s));
d[i+2] = clamp255(Math.round(b * s));
}
}
function applySaturation(imageData, factor = 1.3) {
const d = imageData.data;
for (let i = 0; i < d.length; i += 4) {
const r = d[i], g = d[i+1], b = d[i+2];
const gray = 0.2126*r + 0.7152*g + 0.0722*b;
d[i] = clamp255(Math.round(gray + (r - gray) * factor));
d[i+1] = clamp255(Math.round(gray + (g - gray) * factor));
d[i+2] = clamp255(Math.round(gray + (b - gray) * factor));
}
}
try {
// Works for both JSON and multipart:
// - JSON: req.body is object
// - multipart: req.body fields are strings
const imageUrl = req.body?.imageUrl;
const outW = num(req.body?.outW, 1200);
const outH = num(req.body?.outH, 1600);
const fit = (req.body?.fit ?? "contain"); // cover | contain
const format = (req.body?.format ?? "jpeg"); // png | jpeg
const gamma = num(req.body?.gamma, 0.9);
const saturation = num(req.body?.saturation, 1.1);
const lift = num(req.body?.lift, 10);
const liftThreshold = num(req.body?.liftThreshold, 90);
const epd_optimize = num(req.body?.epd_optimize, 0);
const color_optimize = num(req.body?.color_optimize, 1);
// 1) Load image: either uploaded file or URL
let img;
if (req.file?.buffer) {
img = await loadImage(req.file.buffer);
} else if (imageUrl) {
img = await loadImage(imageUrl);
} else {
return res.status(400).json({
error: "Provide either imageUrl (JSON) or an uploaded file field named 'image' (multipart/form-data).",
});
}
// 2) Input canvas
const inputCanvas = createCanvas(outW, outH);
const ictx = inputCanvas.getContext("2d");
// optional: white background (otherwise black borders may appear with contain)
ictx.fillStyle = "#FFFFFF";
ictx.fillRect(0, 0, outW, outH);
// Scale and draw image
const scaleContain = Math.min(outW / img.width, outH / img.height);
const scaleCover = Math.max(outW / img.width, outH / img.height);
const scale = fit === "cover" ? scaleCover : scaleContain;
const drawW = Math.round(img.width * scale);
const drawH = Math.round(img.height * scale);
const dx = Math.floor((outW - drawW) / 2);
const dy = Math.floor((outH - drawH) / 2);
ictx.imageSmoothingEnabled = true;
ictx.imageSmoothingQuality = "high";
ictx.drawImage(img, dx, dy, drawW, drawH);
if (color_optimize) {
let imageData = ictx.getImageData(0, 0, outW, outH);
liftShadowsSoft(imageData, lift, liftThreshold);
applyGammaOnLuma(imageData, gamma);
applySaturation(imageData, saturation);
ictx.putImageData(imageData, 0, 0);
}
let buf;
if (epd_optimize) {
// 2) Output canvases
const ditheredCanvas = createCanvas(outW, outH);
const ditheredCanvasWithDeviceColors = createCanvas(outW, outH);
const config = {
"palette": "aitjcizeSpectra6Palette",
"ditherOptions": {
"processingPreset": "balanced",
"ditheringType": "quantizationOnly",
"colorMatching": "lab",
"toneMapping": {
"mode": "contrast",
"exposure": 1.05,
"saturation": 1,
"contrast": 1.18
},
"dynamicRangeCompression": {
"mode": "display",
"strength": 0.75
}
}
};
const palette = aitjcizeSpectra6Palette;
// Dither the image
await ditherImage(inputCanvas, ditheredCanvas, {
...config.ditherOptions,
palette,
});
// Convert the colors to the display's native colors
replaceColors(ditheredCanvas, ditheredCanvasWithDeviceColors, palette);
buf = ditheredCanvasWithDeviceColors.toBuffer("image/" + format, { quality: 0.90 });
} else {
buf = inputCanvas.toBuffer("image/" + format, {
quality: 0.90,
progressive: false,
chromaSubsampling: true
});
}
res.setHeader("Content-Type", "image/" + format);
res.setHeader("Cache-Control", "no-store");
return res.status(200).send(buf);
} catch (err) {
return res.status(500).json({ error: String(err?.message ?? err) });
}
});
const PORT = process.env.PORT || 3030;
app.listen(PORT, () => console.log(`eink-optimize listening on :${PORT}`));