qrdx 0.0.46 → 0.0.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +358 -300
- package/dist/index.js +27 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +27 -7
- package/dist/index.mjs.map +1 -1
- package/dist/qr-code-canvas.js +12 -0
- package/dist/qr-code-canvas.js.map +1 -0
- package/dist/qr-code-canvas.mjs +12 -0
- package/dist/qr-code-canvas.mjs.map +1 -0
- package/dist/src/api.d.ts.map +1 -1
- package/dist/src/art-trace.d.ts +46 -0
- package/dist/src/art-trace.d.ts.map +1 -0
- package/dist/src/art.d.ts +138 -0
- package/dist/src/art.d.ts.map +1 -0
- package/dist/src/body-patterns.d.ts +34 -0
- package/dist/src/body-patterns.d.ts.map +1 -0
- package/dist/src/codegen.d.ts +5 -5
- package/dist/src/codegen.d.ts.map +1 -1
- package/dist/src/codeword-map.d.ts +40 -0
- package/dist/src/codeword-map.d.ts.map +1 -0
- package/dist/src/constants.d.ts +4 -7
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/corner-dot.d.ts +3 -1
- package/dist/src/corner-dot.d.ts.map +1 -1
- package/dist/src/corner-eye.d.ts +5 -2
- package/dist/src/corner-eye.d.ts.map +1 -1
- package/dist/src/detection.d.ts.map +1 -1
- package/dist/src/download.d.ts +50 -6
- package/dist/src/download.d.ts.map +1 -1
- package/dist/src/eps.d.ts +62 -0
- package/dist/src/eps.d.ts.map +1 -0
- package/dist/src/frame-icons.d.ts +11 -0
- package/dist/src/frame-icons.d.ts.map +1 -0
- package/dist/src/frame-import.d.ts +61 -0
- package/dist/src/frame-import.d.ts.map +1 -0
- package/dist/src/frame-spec.d.ts +24 -0
- package/dist/src/frame-spec.d.ts.map +1 -0
- package/dist/src/frame-styles.d.ts +50 -0
- package/dist/src/frame-styles.d.ts.map +1 -0
- package/dist/src/frame.d.ts +126 -0
- package/dist/src/frame.d.ts.map +1 -0
- package/dist/src/frames/builtin.d.ts +8 -0
- package/dist/src/frames/builtin.d.ts.map +1 -0
- package/dist/src/frames/official.d.ts +18 -0
- package/dist/src/frames/official.d.ts.map +1 -0
- package/dist/src/helpers.d.ts +15 -2
- package/dist/src/helpers.d.ts.map +1 -1
- package/dist/src/index.d.ts +25 -13
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/logo-budget.d.ts +54 -0
- package/dist/src/logo-budget.d.ts.map +1 -0
- package/dist/src/logo-cleanup.d.ts +25 -0
- package/dist/src/logo-cleanup.d.ts.map +1 -0
- package/dist/src/logo.d.ts +28 -0
- package/dist/src/logo.d.ts.map +1 -0
- package/dist/src/print.d.ts +73 -0
- package/dist/src/print.d.ts.map +1 -0
- package/dist/src/qr-code-canvas.d.ts +13 -0
- package/dist/src/qr-code-canvas.d.ts.map +1 -0
- package/dist/src/qr-code.d.ts +4 -2
- package/dist/src/qr-code.d.ts.map +1 -1
- package/dist/src/qr-outline.d.ts +41 -0
- package/dist/src/qr-outline.d.ts.map +1 -0
- package/dist/src/qr-shape.d.ts +72 -0
- package/dist/src/qr-shape.d.ts.map +1 -0
- package/dist/src/scan-risk.d.ts +40 -0
- package/dist/src/scan-risk.d.ts.map +1 -0
- package/dist/src/scan-score.d.ts +154 -0
- package/dist/src/scan-score.d.ts.map +1 -0
- package/dist/src/shapes.d.ts +36 -0
- package/dist/src/shapes.d.ts.map +1 -0
- package/dist/src/silhouette.d.ts +28 -0
- package/dist/src/silhouette.d.ts.map +1 -0
- package/dist/src/utils/color.d.ts.map +1 -1
- package/dist/src/utils/fmt.d.ts +24 -0
- package/dist/src/utils/fmt.d.ts.map +1 -0
- package/dist/src/utils/paint.d.ts +80 -0
- package/dist/src/utils/paint.d.ts.map +1 -0
- package/dist/src/utils/parse-color.d.ts +21 -0
- package/dist/src/utils/parse-color.d.ts.map +1 -0
- package/dist/src/utils/path-data.d.ts +24 -0
- package/dist/src/utils/path-data.d.ts.map +1 -0
- package/dist/src/utils/png.d.ts +16 -0
- package/dist/src/utils/png.d.ts.map +1 -0
- package/dist/src/utils/polygon-clip.d.ts +26 -0
- package/dist/src/utils/polygon-clip.d.ts.map +1 -0
- package/dist/src/utils/print-shared.d.ts +20 -0
- package/dist/src/utils/print-shared.d.ts.map +1 -0
- package/dist/src/utils/svg-geometry.d.ts +49 -0
- package/dist/src/utils/svg-geometry.d.ts.map +1 -0
- package/dist/src/utils/svg-gradient.d.ts +59 -0
- package/dist/src/utils/svg-gradient.d.ts.map +1 -0
- package/dist/src/utils/svg-painter.d.ts +152 -0
- package/dist/src/utils/svg-painter.d.ts.map +1 -0
- package/dist/src/utils/webp.d.ts +25 -0
- package/dist/src/utils/webp.d.ts.map +1 -0
- package/dist/src/utils.d.ts +18 -2
- package/dist/src/utils.d.ts.map +1 -1
- package/dist/src/webp.d.ts +19 -0
- package/dist/src/webp.d.ts.map +1 -0
- package/dist/types/art.d.ts +64 -0
- package/dist/types/art.d.ts.map +1 -0
- package/dist/types/color.d.ts +125 -7
- package/dist/types/color.d.ts.map +1 -1
- package/dist/types/corner-dot.d.ts +52 -2
- package/dist/types/corner-dot.d.ts.map +1 -1
- package/dist/types/corner-eye.d.ts +43 -2
- package/dist/types/corner-eye.d.ts.map +1 -1
- package/dist/types/frame-spec.d.ts +3509 -0
- package/dist/types/frame-spec.d.ts.map +1 -0
- package/dist/types/frame.d.ts +68 -0
- package/dist/types/frame.d.ts.map +1 -0
- package/dist/types/image-pattern.d.ts +15 -1
- package/dist/types/image-pattern.d.ts.map +1 -1
- package/dist/types/index.d.ts +15 -9
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +6 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/index.mjs +6 -0
- package/dist/types/index.mjs.map +1 -0
- package/dist/types/qr.d.ts +1684 -4
- package/dist/types/qr.d.ts.map +1 -1
- package/dist/types/template.d.ts +2 -2
- package/dist/types/template.d.ts.map +1 -1
- package/package.json +70 -25
- package/src/api.tsx +67 -17
- package/src/art-trace.ts +554 -0
- package/src/art.tsx +2226 -0
- package/src/body-patterns.tsx +389 -0
- package/src/codegen.ts +10 -5
- package/src/codeword-map.ts +265 -0
- package/src/constants.ts +4 -8
- package/src/corner-dot.tsx +209 -33
- package/src/corner-eye.ts +328 -60
- package/src/detection.ts +5 -11
- package/src/download.tsx +174 -70
- package/src/eps.ts +701 -0
- package/src/frame-icons.ts +325 -0
- package/src/frame-import.ts +1198 -0
- package/src/frame-spec.ts +518 -0
- package/src/frame-styles.ts +1095 -0
- package/src/frame.tsx +630 -0
- package/src/frames/builtin/banner-bottom.json +58 -0
- package/src/frames/builtin/circle.json +81 -0
- package/src/frames/builtin/rounded-border.json +60 -0
- package/src/frames/builtin/ticket.json +51 -0
- package/src/frames/builtin.ts +20 -0
- package/src/frames/official/attendance.json +110 -0
- package/src/frames/official/audio-guide.json +95 -0
- package/src/frames/official/book-now.json +103 -0
- package/src/frames/official/check-in.json +110 -0
- package/src/frames/official/christmas.json +131 -0
- package/src/frames/official/donate.json +77 -0
- package/src/frames/official/event-ticket.json +77 -0
- package/src/frames/official/feedback-bubble.json +73 -0
- package/src/frames/official/follow-us.json +83 -0
- package/src/frames/official/get-the-app.json +107 -0
- package/src/frames/official/halloween.json +80 -0
- package/src/frames/official/new-year.json +94 -0
- package/src/frames/official/order-at-table.json +86 -0
- package/src/frames/official/product-info.json +119 -0
- package/src/frames/official/register-product.json +77 -0
- package/src/frames/official/review-us.json +127 -0
- package/src/frames/official/rsvp-card.json +112 -0
- package/src/frames/official/save-contact.json +117 -0
- package/src/frames/official/scan-to-pay.json +94 -0
- package/src/frames/official/shop-window.json +81 -0
- package/src/frames/official/sign-rider.json +81 -0
- package/src/frames/official/table-tent.json +75 -0
- package/src/frames/official/wifi-card.json +89 -0
- package/src/frames/official/winter.json +142 -0
- package/src/frames/official.ts +77 -0
- package/src/helpers.ts +168 -11
- package/src/index.tsx +150 -172
- package/src/logo-budget.ts +226 -0
- package/src/logo-cleanup.ts +146 -0
- package/src/logo.tsx +137 -0
- package/src/print.ts +794 -0
- package/src/qr-code-canvas.tsx +241 -0
- package/src/qr-code.tsx +51 -16
- package/src/qr-outline.ts +511 -0
- package/src/qr-shape.ts +255 -0
- package/src/scan-risk.ts +197 -0
- package/src/scan-score.ts +1629 -0
- package/src/shapes.ts +169 -0
- package/src/silhouette.ts +334 -0
- package/src/utils/color.ts +10 -1
- package/src/utils/fmt.ts +59 -0
- package/src/utils/paint.ts +317 -0
- package/src/utils/parse-color.ts +135 -0
- package/src/utils/path-data.ts +182 -0
- package/src/utils/png.ts +175 -0
- package/src/utils/polygon-clip.ts +163 -0
- package/src/utils/print-shared.ts +74 -0
- package/src/utils/svg-geometry.ts +838 -0
- package/src/utils/svg-gradient.ts +407 -0
- package/src/utils/svg-painter.ts +946 -0
- package/src/utils/webp.ts +556 -0
- package/src/utils.tsx +794 -385
- package/src/webp.ts +84 -0
- package/types/art.ts +74 -0
- package/types/color.ts +132 -12
- package/types/corner-dot.ts +41 -4
- package/types/corner-eye.ts +31 -4
- package/types/frame-spec.ts +748 -0
- package/types/frame.ts +67 -0
- package/types/image-pattern.ts +15 -0
- package/types/index.ts +106 -4
- package/types/qr.ts +180 -2
- package/types/template.ts +2 -2
- package/dist/cli.js +0 -4319
|
@@ -0,0 +1,1629 @@
|
|
|
1
|
+
/** biome-ignore-all lint/style/noMagicNumbers: scoring weights and thresholds */
|
|
2
|
+
import type { QRCode as JsQRResult } from "jsqr";
|
|
3
|
+
import type { ColorConfig, QRProps } from "../types";
|
|
4
|
+
import { normalizeColorConfig } from "../types/color";
|
|
5
|
+
import { EYE_POSITIONS } from "../types/qr";
|
|
6
|
+
import type { QRArtPixels } from "./art";
|
|
7
|
+
import qrcodegen from "./codegen";
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_BGCOLOR,
|
|
10
|
+
DEFAULT_FGCOLOR,
|
|
11
|
+
DEFAULT_MARGIN,
|
|
12
|
+
DEFAULT_SIZE,
|
|
13
|
+
ERROR_LEVEL_MAP,
|
|
14
|
+
} from "./constants";
|
|
15
|
+
import { handleImageLoad } from "./detection";
|
|
16
|
+
import { withQRSize } from "./download";
|
|
17
|
+
import { getFrameDimensions, getFrameGapRatio, isFrameActive } from "./frame";
|
|
18
|
+
import { getQRAsSVGDataUri } from "./index";
|
|
19
|
+
import { getLogoBlockDamage } from "./logo-budget";
|
|
20
|
+
import { circleQuietZone, getLayoutMargin, isShapedCode } from "./qr-shape";
|
|
21
|
+
import { getStylePairRisk } from "./scan-risk";
|
|
22
|
+
import { getImageSettings, getLuminance, resolveErrorLevel } from "./utils";
|
|
23
|
+
import { parseColor, type RGBAColor } from "./utils/parse-color";
|
|
24
|
+
|
|
25
|
+
export type ScanGrade = "great" | "ok" | "risky" | "fails";
|
|
26
|
+
|
|
27
|
+
export interface ScanCheck {
|
|
28
|
+
id: string;
|
|
29
|
+
/** False only for a problem; a skipped check is `true` so it costs nothing. */
|
|
30
|
+
passed: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* The check couldn't run on this input (a photo cropped too tight to see
|
|
33
|
+
* the quiet zone): neither passed nor failed. Show it as "not checked".
|
|
34
|
+
*/
|
|
35
|
+
skipped?: boolean;
|
|
36
|
+
message: string;
|
|
37
|
+
/** How to fix a failed check */
|
|
38
|
+
fix?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface ScanScoreResult {
|
|
42
|
+
/** 0–100 */
|
|
43
|
+
score: number;
|
|
44
|
+
grade: ScanGrade;
|
|
45
|
+
checks: ScanCheck[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface ImageScanScoreResult extends ScanScoreResult {
|
|
49
|
+
/** Decoded content, or null when no QR code was found */
|
|
50
|
+
data: string | null;
|
|
51
|
+
/** QR version (1–40) when the code could be located */
|
|
52
|
+
version: number | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface ScanScoreOptions {
|
|
56
|
+
/** QR code widths in pixels to test (default 96, 160, 320) */
|
|
57
|
+
sizes?: number[];
|
|
58
|
+
signal?: AbortSignal;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Widths (px) of the QR code that `getScanScore` decodes by default. */
|
|
62
|
+
export const SCAN_TEST_SIZES = [96, 160, 320] as const;
|
|
63
|
+
|
|
64
|
+
// Code width (px) the artwork is rendered at before downscaling to test sizes.
|
|
65
|
+
const SOURCE_SIZE = 640;
|
|
66
|
+
|
|
67
|
+
type Decoder = typeof import("jsqr").default;
|
|
68
|
+
type DecodeState = "pass" | "fragile" | "fail";
|
|
69
|
+
|
|
70
|
+
function assertBrowser() {
|
|
71
|
+
if (typeof document === "undefined") {
|
|
72
|
+
throw new Error("Scan scoring needs a browser (canvas + image decoding)");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function throwIfAborted(signal?: AbortSignal) {
|
|
77
|
+
if (signal?.aborted) {
|
|
78
|
+
throw new DOMException("Scan scoring was aborted", "AbortError");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const nextTick = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
83
|
+
|
|
84
|
+
async function loadDecoder(): Promise<Decoder> {
|
|
85
|
+
const { default: jsQR } = await import("jsqr");
|
|
86
|
+
return jsQR;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function matches(result: JsQRResult | null, value: string): boolean {
|
|
90
|
+
if (!result) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
if (result.data === value) {
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
return (
|
|
98
|
+
new TextDecoder().decode(Uint8Array.from(result.binaryData)) === value
|
|
99
|
+
);
|
|
100
|
+
} catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Camera-like degradation, in place: contrast loss plus a blur of about a
|
|
107
|
+
* quarter module (two box-blur passes approximate a Gaussian).
|
|
108
|
+
*/
|
|
109
|
+
function simulateCamera(image: ImageData, modulePx: number, contrast = 0.7) {
|
|
110
|
+
const { data, width, height } = image;
|
|
111
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
112
|
+
for (let c = 0; c < 3; c++) {
|
|
113
|
+
data[i + c] = 128 + ((data[i + c] as number) - 128) * contrast;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const radius = Math.max(1, Math.round(modulePx * 0.25));
|
|
117
|
+
const buffer = new Float32Array(width * height * 3);
|
|
118
|
+
const blur = (horizontal: boolean) => {
|
|
119
|
+
const lines = horizontal ? height : width;
|
|
120
|
+
const length = horizontal ? width : height;
|
|
121
|
+
const index = (line: number, position: number) =>
|
|
122
|
+
horizontal ? line * width + position : position * width + line;
|
|
123
|
+
const sums = [0, 0, 0];
|
|
124
|
+
for (let line = 0; line < lines; line++) {
|
|
125
|
+
sums.fill(0);
|
|
126
|
+
// Sliding window with clamped edges
|
|
127
|
+
for (let k = -radius; k <= radius; k++) {
|
|
128
|
+
const p = index(line, Math.min(Math.max(k, 0), length - 1)) * 4;
|
|
129
|
+
for (let c = 0; c < 3; c++) {
|
|
130
|
+
sums[c] = (sums[c] as number) + (data[p + c] as number);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
for (let position = 0; position < length; position++) {
|
|
134
|
+
const target = index(line, position) * 3;
|
|
135
|
+
for (let c = 0; c < 3; c++) {
|
|
136
|
+
buffer[target + c] = (sums[c] as number) / (2 * radius + 1);
|
|
137
|
+
}
|
|
138
|
+
const out = index(line, Math.max(position - radius, 0)) * 4;
|
|
139
|
+
const into =
|
|
140
|
+
index(line, Math.min(position + radius + 1, length - 1)) * 4;
|
|
141
|
+
for (let c = 0; c < 3; c++) {
|
|
142
|
+
sums[c] =
|
|
143
|
+
(sums[c] as number) -
|
|
144
|
+
(data[out + c] as number) +
|
|
145
|
+
(data[into + c] as number);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
for (let i = 0; i < width * height; i++) {
|
|
150
|
+
for (let c = 0; c < 3; c++) {
|
|
151
|
+
data[i * 4 + c] = buffer[i * 3 + c] as number;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
156
|
+
blur(true);
|
|
157
|
+
blur(false);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function createCanvas(width: number, height: number) {
|
|
162
|
+
const canvas = document.createElement("canvas");
|
|
163
|
+
canvas.width = Math.max(1, Math.round(width));
|
|
164
|
+
canvas.height = Math.max(1, Math.round(height));
|
|
165
|
+
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
|
166
|
+
if (!ctx) {
|
|
167
|
+
throw new Error("Could not get canvas context");
|
|
168
|
+
}
|
|
169
|
+
ctx.imageSmoothingEnabled = true;
|
|
170
|
+
ctx.imageSmoothingQuality = "high";
|
|
171
|
+
return { canvas, ctx };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// A phone tries many frames at slightly different distances.
|
|
175
|
+
const ATTEMPT_SCALES = [0.9, 1, 1.1];
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Decodes the code at `size` px wide a few times at slightly different
|
|
179
|
+
* scales through the camera simulation. `draw` returns the pixels with the
|
|
180
|
+
* code `codeWidth` px wide.
|
|
181
|
+
*/
|
|
182
|
+
function decodeAtSize(
|
|
183
|
+
jsQR: Decoder,
|
|
184
|
+
draw: (codeWidth: number) => ImageData,
|
|
185
|
+
size: number,
|
|
186
|
+
moduleCount: number,
|
|
187
|
+
expected: (result: JsQRResult | null) => boolean
|
|
188
|
+
): DecodeState {
|
|
189
|
+
let hits = 0;
|
|
190
|
+
for (const scale of ATTEMPT_SCALES) {
|
|
191
|
+
const codeWidth = size * scale;
|
|
192
|
+
const image = draw(codeWidth);
|
|
193
|
+
simulateCamera(image, codeWidth / moduleCount);
|
|
194
|
+
if (expected(jsQR(image.data, image.width, image.height))) {
|
|
195
|
+
hits++;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (hits >= 2) {
|
|
199
|
+
return "pass";
|
|
200
|
+
}
|
|
201
|
+
return hits === 1 ? "fragile" : "fail";
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const SIZE_LABELS: Record<string, string> = {
|
|
205
|
+
small: "small print or far away",
|
|
206
|
+
medium: "typical phone distance",
|
|
207
|
+
large: "close up",
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
function sizeLabel(size: number, sizes: number[]): string {
|
|
211
|
+
if (size === sizes[0] && sizes.length > 1) {
|
|
212
|
+
return SIZE_LABELS.small as string;
|
|
213
|
+
}
|
|
214
|
+
if (size === sizes.at(-1)) {
|
|
215
|
+
return SIZE_LABELS.large as string;
|
|
216
|
+
}
|
|
217
|
+
return SIZE_LABELS.medium as string;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Penalty for a failed decode at a size: big codes matter most. */
|
|
221
|
+
function decodePenalty(index: number, count: number, state: DecodeState) {
|
|
222
|
+
if (state === "pass") {
|
|
223
|
+
return 0;
|
|
224
|
+
}
|
|
225
|
+
const weights = count === 1 ? [45] : count === 2 ? [20, 45] : [15, 20, 45];
|
|
226
|
+
const weight =
|
|
227
|
+
weights[
|
|
228
|
+
Math.round((index * (weights.length - 1)) / Math.max(count - 1, 1))
|
|
229
|
+
] ?? 20;
|
|
230
|
+
return state === "fragile" ? Math.round(weight / 2) : weight;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function decodeCheck(
|
|
234
|
+
size: number,
|
|
235
|
+
sizes: number[],
|
|
236
|
+
state: DecodeState
|
|
237
|
+
): ScanCheck {
|
|
238
|
+
const label = `${size} px (${sizeLabel(size, sizes)})`;
|
|
239
|
+
if (state === "pass") {
|
|
240
|
+
return {
|
|
241
|
+
id: `decode-${size}`,
|
|
242
|
+
passed: true,
|
|
243
|
+
message: `Reads at ${label}, with camera blur`,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
id: `decode-${size}`,
|
|
248
|
+
passed: false,
|
|
249
|
+
message:
|
|
250
|
+
state === "fragile"
|
|
251
|
+
? `Reads at ${label} only some of the time`
|
|
252
|
+
: `Doesn't read at ${label}`,
|
|
253
|
+
fix:
|
|
254
|
+
size === sizes[0]
|
|
255
|
+
? "Print it bigger, shorten the content (fewer modules) or use solid square dots"
|
|
256
|
+
: "Raise the contrast, use bigger dots or a simpler eye shape",
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function gradeFor(score: number, fails: boolean): ScanGrade {
|
|
261
|
+
if (fails) {
|
|
262
|
+
return "fails";
|
|
263
|
+
}
|
|
264
|
+
if (score >= 85) {
|
|
265
|
+
return "great";
|
|
266
|
+
}
|
|
267
|
+
if (score >= 65) {
|
|
268
|
+
return "ok";
|
|
269
|
+
}
|
|
270
|
+
return "risky";
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The lightest and darkest a picture gets, as "#rrggbb": the colors at its
|
|
275
|
+
* 90th and 10th percentile luminance. The contrast check judges an image
|
|
276
|
+
* fill by these (see getImageTones).
|
|
277
|
+
*/
|
|
278
|
+
export interface ImageTones {
|
|
279
|
+
light: string;
|
|
280
|
+
dark: string;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Image tones by image `src`. */
|
|
284
|
+
export type ImageToneMap = Record<string, ImageTones>;
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* The colors a paint shows: the color, every gradient stop, or an image
|
|
288
|
+
* fill's tones at its opacity over its underlay. An image whose tones aren't
|
|
289
|
+
* known counts as its underlay (or not at all, without one).
|
|
290
|
+
*/
|
|
291
|
+
function colorStops(
|
|
292
|
+
color: ColorConfig | undefined,
|
|
293
|
+
fallback: string,
|
|
294
|
+
tones?: ImageToneMap
|
|
295
|
+
): string[] {
|
|
296
|
+
const normalized = normalizeColorConfig(color, fallback);
|
|
297
|
+
if (normalized.type === "solid") {
|
|
298
|
+
return [normalized.color];
|
|
299
|
+
}
|
|
300
|
+
if (normalized.type !== "image") {
|
|
301
|
+
return normalized.stops.map((stop) => stop.color);
|
|
302
|
+
}
|
|
303
|
+
const underlay = normalized.underlay ? toRGBA(normalized.underlay) : null;
|
|
304
|
+
const known = tones?.[normalized.src];
|
|
305
|
+
if (!known) {
|
|
306
|
+
return normalized.underlay ? [normalized.underlay] : [];
|
|
307
|
+
}
|
|
308
|
+
const opacity = normalized.opacity ?? 1;
|
|
309
|
+
return [known.light, known.dark].flatMap((tone) => {
|
|
310
|
+
const parsed = toRGBA(tone);
|
|
311
|
+
if (!parsed) {
|
|
312
|
+
return [];
|
|
313
|
+
}
|
|
314
|
+
const picture = { ...parsed, a: parsed.a * opacity };
|
|
315
|
+
if (!underlay) {
|
|
316
|
+
return [rgbaString(picture)];
|
|
317
|
+
}
|
|
318
|
+
// Picture over the underlay: alpha adds up as source-over does
|
|
319
|
+
const a = picture.a + underlay.a * (1 - picture.a);
|
|
320
|
+
const mix = (p: number, u: number) =>
|
|
321
|
+
a > 0 ? (p * picture.a + u * underlay.a * (1 - picture.a)) / a : 0;
|
|
322
|
+
return [
|
|
323
|
+
rgbaString({
|
|
324
|
+
r: mix(picture.r, underlay.r),
|
|
325
|
+
g: mix(picture.g, underlay.g),
|
|
326
|
+
b: mix(picture.b, underlay.b),
|
|
327
|
+
a,
|
|
328
|
+
}),
|
|
329
|
+
];
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const rgbaString = ({ r, g, b, a }: RGBAColor) =>
|
|
334
|
+
`rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${Math.round(a * 1000) / 1000})`;
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Image tones from RGBA pixels (alpha below half skipped): the average color
|
|
338
|
+
* of the darkest and the lightest tenth of the pixels.
|
|
339
|
+
*/
|
|
340
|
+
export function getImageTonesFromPixels(pixels: {
|
|
341
|
+
data: ArrayLike<number>;
|
|
342
|
+
width: number;
|
|
343
|
+
height: number;
|
|
344
|
+
}): ImageTones | null {
|
|
345
|
+
const samples: { lum: number; r: number; g: number; b: number }[] = [];
|
|
346
|
+
const count = pixels.width * pixels.height;
|
|
347
|
+
for (let i = 0; i < count; i++) {
|
|
348
|
+
const r = pixels.data[i * 4] as number;
|
|
349
|
+
const g = pixels.data[i * 4 + 1] as number;
|
|
350
|
+
const b = pixels.data[i * 4 + 2] as number;
|
|
351
|
+
const a = pixels.data[i * 4 + 3] as number;
|
|
352
|
+
if (a < 128) {
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
samples.push({ lum: getLuminance(r, g, b), r, g, b });
|
|
356
|
+
}
|
|
357
|
+
if (samples.length === 0) {
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
samples.sort((x, y) => x.lum - y.lum);
|
|
361
|
+
const tenth = Math.max(1, Math.round(samples.length / 10));
|
|
362
|
+
const average = (list: typeof samples) => {
|
|
363
|
+
const sum = list.reduce(
|
|
364
|
+
(total, item) => ({
|
|
365
|
+
r: total.r + item.r,
|
|
366
|
+
g: total.g + item.g,
|
|
367
|
+
b: total.b + item.b,
|
|
368
|
+
}),
|
|
369
|
+
{ r: 0, g: 0, b: 0 }
|
|
370
|
+
);
|
|
371
|
+
const hex = (value: number) =>
|
|
372
|
+
Math.round(value / list.length)
|
|
373
|
+
.toString(16)
|
|
374
|
+
.padStart(2, "0");
|
|
375
|
+
return `#${hex(sum.r)}${hex(sum.g)}${hex(sum.b)}`;
|
|
376
|
+
};
|
|
377
|
+
return {
|
|
378
|
+
dark: average(samples.slice(0, tenth)),
|
|
379
|
+
light: average(samples.slice(-tenth)),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Image tones of a picture (browser only): drawn at 64 px and sampled. */
|
|
384
|
+
export async function getImageTones(src: string): Promise<ImageTones | null> {
|
|
385
|
+
assertBrowser();
|
|
386
|
+
const img = await loadImage(src);
|
|
387
|
+
const { canvas, ctx } = createCanvas(64, 64);
|
|
388
|
+
ctx.drawImage(img, 0, 0, 64, 64);
|
|
389
|
+
const tones = getImageTonesFromPixels(ctx.getImageData(0, 0, 64, 64));
|
|
390
|
+
canvas.remove();
|
|
391
|
+
return tones;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Every image fill's `src` in the props. */
|
|
395
|
+
function imageSources(props: QRProps): string[] {
|
|
396
|
+
const paints = [
|
|
397
|
+
props.bgColor,
|
|
398
|
+
props.fgColor,
|
|
399
|
+
props.eyeColor,
|
|
400
|
+
props.dotColor,
|
|
401
|
+
...EYE_POSITIONS.flatMap((position) => [
|
|
402
|
+
props.eyeColors?.[position]?.outer,
|
|
403
|
+
props.eyeColors?.[position]?.inner,
|
|
404
|
+
]),
|
|
405
|
+
];
|
|
406
|
+
const sources = new Set<string>();
|
|
407
|
+
for (const paint of paints) {
|
|
408
|
+
if (typeof paint === "object" && paint?.type === "image") {
|
|
409
|
+
sources.add(paint.src);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return [...sources];
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
let normalizeCtx: CanvasRenderingContext2D | null = null;
|
|
416
|
+
|
|
417
|
+
/** parseColor, falling back to the browser's own color parser. */
|
|
418
|
+
function toRGBA(color: string): RGBAColor | null {
|
|
419
|
+
const parsed = parseColor(color);
|
|
420
|
+
if (parsed || typeof document === "undefined") {
|
|
421
|
+
return parsed;
|
|
422
|
+
}
|
|
423
|
+
normalizeCtx ??= document.createElement("canvas").getContext("2d");
|
|
424
|
+
if (!normalizeCtx) {
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
normalizeCtx.fillStyle = "#010203";
|
|
428
|
+
normalizeCtx.fillStyle = color;
|
|
429
|
+
const normalized = String(normalizeCtx.fillStyle);
|
|
430
|
+
return normalized === "#010203" ? null : parseColor(normalized);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const luminanceOf = (color: RGBAColor) =>
|
|
434
|
+
getLuminance(color.r, color.g, color.b);
|
|
435
|
+
|
|
436
|
+
const ratioOf = (a: number, b: number) =>
|
|
437
|
+
(Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
|
|
438
|
+
|
|
439
|
+
/** Contrast at or above this scans reliably (the scan score's pass line). */
|
|
440
|
+
export const SCAN_CONTRAST_MIN = 4.5;
|
|
441
|
+
/** Below this the score costs 30 points instead of 10. */
|
|
442
|
+
export const SCAN_CONTRAST_LOW = 3;
|
|
443
|
+
/** Below this the code fails the scan score outright. */
|
|
444
|
+
export const SCAN_CONTRAST_FAIL = 1.5;
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Contrast a picture needs to scan reliably, in the code or behind it: its
|
|
448
|
+
* detail reads as noise at phone distances. Measured with the sample photos
|
|
449
|
+
* through the camera model (tests/export-image.test.ts): every picture in
|
|
450
|
+
* the dots decoded from 6.5:1, and busy photos behind the dots from 12:1.
|
|
451
|
+
*/
|
|
452
|
+
export const SCAN_IMAGE_CONTRAST_MIN = { code: 7, background: 12 } as const;
|
|
453
|
+
|
|
454
|
+
export interface ScanContrast {
|
|
455
|
+
/**
|
|
456
|
+
* Worst contrast between any code color and any background color (≥ 1);
|
|
457
|
+
* Infinity when no code color parses
|
|
458
|
+
*/
|
|
459
|
+
ratio: number;
|
|
460
|
+
/**
|
|
461
|
+
* What `ratio`'s pair needs: SCAN_CONTRAST_MIN for colors, more when a
|
|
462
|
+
* picture is involved (SCAN_IMAGE_CONTRAST_MIN). The low and fail lines
|
|
463
|
+
* scale with it.
|
|
464
|
+
*/
|
|
465
|
+
required: number;
|
|
466
|
+
/** Some code color is lighter than the background */
|
|
467
|
+
inverted: boolean;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const WHITE: RGBAColor = { r: 255, g: 255, b: 255, a: 1 };
|
|
471
|
+
|
|
472
|
+
/** `color` composited over an opaque `backdrop`. */
|
|
473
|
+
const over = (color: RGBAColor, backdrop: RGBAColor): RGBAColor => ({
|
|
474
|
+
r: color.r * color.a + backdrop.r * (1 - color.a),
|
|
475
|
+
g: color.g * color.a + backdrop.g * (1 - color.a),
|
|
476
|
+
b: color.b * color.a + backdrop.b * (1 - color.a),
|
|
477
|
+
a: 1,
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* The contrast check behind the scan score: the worst WCAG contrast ratio
|
|
482
|
+
* between every code color (foreground, eyes, eye centres and per-eye
|
|
483
|
+
* colors, every gradient stop) and every background color. See-through
|
|
484
|
+
* colors count as they look: the background over white paper, the code
|
|
485
|
+
* over the background.
|
|
486
|
+
*/
|
|
487
|
+
export function getScanContrast(
|
|
488
|
+
props: QRProps,
|
|
489
|
+
options: { imageTones?: ImageToneMap } = {}
|
|
490
|
+
): ScanContrast {
|
|
491
|
+
const tones = options.imageTones;
|
|
492
|
+
// Each color a part shows, and whether it comes from a picture
|
|
493
|
+
const samples = (
|
|
494
|
+
color: ColorConfig | undefined,
|
|
495
|
+
fallback: string
|
|
496
|
+
): { color: string; picture: boolean }[] => {
|
|
497
|
+
const picture = typeof color === "object" && color?.type === "image";
|
|
498
|
+
return colorStops(color, fallback, tones).map((item) => ({
|
|
499
|
+
color: item,
|
|
500
|
+
picture,
|
|
501
|
+
}));
|
|
502
|
+
};
|
|
503
|
+
const fg = props.fgColor ?? DEFAULT_FGCOLOR;
|
|
504
|
+
// Per-eye colors replace eyeColor / dotColor on that eye only
|
|
505
|
+
const perEye = EYE_POSITIONS.flatMap((position) => {
|
|
506
|
+
const eye = props.eyeColors?.[position];
|
|
507
|
+
return [
|
|
508
|
+
...(eye?.outer ? samples(eye.outer, DEFAULT_FGCOLOR) : []),
|
|
509
|
+
...(eye?.inner ? samples(eye.inner, DEFAULT_FGCOLOR) : []),
|
|
510
|
+
];
|
|
511
|
+
});
|
|
512
|
+
const darkColors = [
|
|
513
|
+
...samples(fg, DEFAULT_FGCOLOR),
|
|
514
|
+
...samples(props.eyeColor ?? fg, DEFAULT_FGCOLOR),
|
|
515
|
+
...samples(props.dotColor ?? fg, DEFAULT_FGCOLOR),
|
|
516
|
+
...perEye,
|
|
517
|
+
];
|
|
518
|
+
const lightColors = samples(props.bgColor, DEFAULT_BGCOLOR);
|
|
519
|
+
// A transparent background prints on whatever is behind it; assume paper.
|
|
520
|
+
const background = (
|
|
521
|
+
lightColors.length > 0
|
|
522
|
+
? lightColors
|
|
523
|
+
: [{ color: "#ffffff", picture: false }]
|
|
524
|
+
).map((item) => {
|
|
525
|
+
const parsed = toRGBA(item.color);
|
|
526
|
+
return {
|
|
527
|
+
color: parsed ? over(parsed, WHITE) : WHITE,
|
|
528
|
+
picture: item.picture,
|
|
529
|
+
};
|
|
530
|
+
});
|
|
531
|
+
const foreground = darkColors.flatMap((item) => {
|
|
532
|
+
const parsed = toRGBA(item.color);
|
|
533
|
+
return parsed ? [{ color: parsed, picture: item.picture }] : [];
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
// The worst pair relative to what it needs: a picture's detail reads as
|
|
537
|
+
// noise, so pictures need more contrast than flat colors.
|
|
538
|
+
let worst = Number.POSITIVE_INFINITY;
|
|
539
|
+
let required = SCAN_CONTRAST_MIN;
|
|
540
|
+
let inverted = false;
|
|
541
|
+
for (const dark of foreground) {
|
|
542
|
+
for (const light of background) {
|
|
543
|
+
const darkLum = luminanceOf(over(dark.color, light.color));
|
|
544
|
+
const lightLum = luminanceOf(light.color);
|
|
545
|
+
const ratio = ratioOf(darkLum, lightLum);
|
|
546
|
+
const needs = light.picture
|
|
547
|
+
? SCAN_IMAGE_CONTRAST_MIN.background
|
|
548
|
+
: dark.picture
|
|
549
|
+
? SCAN_IMAGE_CONTRAST_MIN.code
|
|
550
|
+
: SCAN_CONTRAST_MIN;
|
|
551
|
+
if (ratio / needs < worst / required) {
|
|
552
|
+
worst = ratio;
|
|
553
|
+
required = needs;
|
|
554
|
+
}
|
|
555
|
+
if (darkLum > lightLum) {
|
|
556
|
+
inverted = true;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
return {
|
|
561
|
+
ratio: Number.isFinite(worst) ? worst : Number.POSITIVE_INFINITY,
|
|
562
|
+
required,
|
|
563
|
+
inverted,
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function contrastChecks(
|
|
568
|
+
props: QRProps,
|
|
569
|
+
imageTones?: ImageToneMap
|
|
570
|
+
): {
|
|
571
|
+
checks: ScanCheck[];
|
|
572
|
+
penalty: number;
|
|
573
|
+
fails: boolean;
|
|
574
|
+
} {
|
|
575
|
+
const {
|
|
576
|
+
ratio: worst,
|
|
577
|
+
inverted,
|
|
578
|
+
required,
|
|
579
|
+
} = getScanContrast(props, { imageTones });
|
|
580
|
+
// No code color parses: nothing to compare
|
|
581
|
+
if (!Number.isFinite(worst)) {
|
|
582
|
+
return { checks: [], penalty: 0, fails: false };
|
|
583
|
+
}
|
|
584
|
+
// The low and fail lines scale with what the pair needs
|
|
585
|
+
const scale = required / SCAN_CONTRAST_MIN;
|
|
586
|
+
const picture = required !== SCAN_CONTRAST_MIN;
|
|
587
|
+
|
|
588
|
+
const ratio = Math.round(worst * 10) / 10;
|
|
589
|
+
const checks: ScanCheck[] = [];
|
|
590
|
+
let penalty = 0;
|
|
591
|
+
if (worst >= required) {
|
|
592
|
+
checks.push({
|
|
593
|
+
id: "contrast",
|
|
594
|
+
passed: true,
|
|
595
|
+
message: `Contrast ${ratio}:1 between code and background`,
|
|
596
|
+
});
|
|
597
|
+
} else {
|
|
598
|
+
penalty =
|
|
599
|
+
worst < SCAN_CONTRAST_FAIL * scale
|
|
600
|
+
? 60
|
|
601
|
+
: worst < SCAN_CONTRAST_LOW * scale
|
|
602
|
+
? 30
|
|
603
|
+
: 10;
|
|
604
|
+
checks.push({
|
|
605
|
+
id: "contrast",
|
|
606
|
+
passed: false,
|
|
607
|
+
message: picture
|
|
608
|
+
? `Low contrast for a picture (${ratio}:1); ${required}:1 or more scans reliably`
|
|
609
|
+
: `Low contrast (${ratio}:1); 4.5:1 or more scans reliably`,
|
|
610
|
+
fix: picture
|
|
611
|
+
? "Lower the picture's opacity over a darker underlay (dots) or a lighter one (background)"
|
|
612
|
+
: "Use a darker code color or a lighter background",
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
if (inverted) {
|
|
616
|
+
penalty += 10;
|
|
617
|
+
checks.push({
|
|
618
|
+
id: "polarity",
|
|
619
|
+
passed: false,
|
|
620
|
+
message:
|
|
621
|
+
"Light code on a dark background; some scanner apps can't read it",
|
|
622
|
+
fix: "Use dark modules on a light background",
|
|
623
|
+
});
|
|
624
|
+
} else {
|
|
625
|
+
checks.push({
|
|
626
|
+
id: "polarity",
|
|
627
|
+
passed: true,
|
|
628
|
+
message: "Dark code on a light background",
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
return {
|
|
632
|
+
checks,
|
|
633
|
+
penalty,
|
|
634
|
+
fails: worst < SCAN_CONTRAST_FAIL * (required / SCAN_CONTRAST_MIN),
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function moduleCount(props: QRProps) {
|
|
639
|
+
return qrcodegen.QrCode.encodeText(
|
|
640
|
+
props.value,
|
|
641
|
+
ERROR_LEVEL_MAP[resolveErrorLevel(props)]
|
|
642
|
+
).getModules();
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function logoCheck(props: QRProps): {
|
|
646
|
+
check: ScanCheck | null;
|
|
647
|
+
penalty: number;
|
|
648
|
+
} {
|
|
649
|
+
const { imageSettings } = props;
|
|
650
|
+
if (!imageSettings) {
|
|
651
|
+
return { check: null, penalty: 0 };
|
|
652
|
+
}
|
|
653
|
+
const cells = moduleCount(props);
|
|
654
|
+
const settings = getImageSettings(
|
|
655
|
+
cells,
|
|
656
|
+
props.size ?? DEFAULT_SIZE,
|
|
657
|
+
getLayoutMargin(cells.length, props.margin ?? DEFAULT_MARGIN, props.shape),
|
|
658
|
+
imageSettings
|
|
659
|
+
);
|
|
660
|
+
if (!settings) {
|
|
661
|
+
return { check: null, penalty: 0 };
|
|
662
|
+
}
|
|
663
|
+
// A moved logo must leave each corner eye and the format information
|
|
664
|
+
// beside it (the 9×9 corner zones) alone: no error correction covers them.
|
|
665
|
+
const box = settings.excavation ?? settings;
|
|
666
|
+
const n = cells.length;
|
|
667
|
+
const zones = [
|
|
668
|
+
[0, 0],
|
|
669
|
+
[n - 8, 0],
|
|
670
|
+
[0, n - 8],
|
|
671
|
+
] as const;
|
|
672
|
+
const coversEye = zones.some(
|
|
673
|
+
([zx, zy]) =>
|
|
674
|
+
box.x < zx + 9 &&
|
|
675
|
+
box.x + box.w > zx &&
|
|
676
|
+
box.y < zy + 9 &&
|
|
677
|
+
box.y + box.h > zy
|
|
678
|
+
);
|
|
679
|
+
// Decoders correct perspective with the alignment pattern nearest the
|
|
680
|
+
// bottom-right corner (version 2 and up, 5×5 around n − 7); others, like
|
|
681
|
+
// the central one in bigger codes, can sit under a centered logo.
|
|
682
|
+
const alignment = n > 21 ? n - 9 : null;
|
|
683
|
+
const coversAlignment =
|
|
684
|
+
alignment !== null &&
|
|
685
|
+
box.x < alignment + 5 &&
|
|
686
|
+
box.x + box.w > alignment &&
|
|
687
|
+
box.y < alignment + 5 &&
|
|
688
|
+
box.y + box.h > alignment;
|
|
689
|
+
if (coversEye || coversAlignment) {
|
|
690
|
+
return {
|
|
691
|
+
check: {
|
|
692
|
+
id: "logo",
|
|
693
|
+
passed: false,
|
|
694
|
+
message: coversEye
|
|
695
|
+
? "The logo covers a corner eye"
|
|
696
|
+
: "The logo covers the small square near the bottom-right corner",
|
|
697
|
+
fix: "Move the logo toward the center or make it smaller",
|
|
698
|
+
},
|
|
699
|
+
penalty: 40,
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
const coverage = (box.w * box.h) / (n * n);
|
|
703
|
+
const level = resolveErrorLevel(props);
|
|
704
|
+
const percent = Math.round(coverage * 100);
|
|
705
|
+
// Count spoiled codewords per Reed–Solomon block, as getQRData caps logos
|
|
706
|
+
// (logo-budget.ts): area alone passes logos small codes can't repair.
|
|
707
|
+
const damage = getLogoBlockDamage(
|
|
708
|
+
{
|
|
709
|
+
value: props.value,
|
|
710
|
+
size: props.size ?? DEFAULT_SIZE,
|
|
711
|
+
margin: props.margin ?? DEFAULT_MARGIN,
|
|
712
|
+
level,
|
|
713
|
+
shape: props.shape,
|
|
714
|
+
},
|
|
715
|
+
imageSettings
|
|
716
|
+
);
|
|
717
|
+
if (!damage || damage.worst <= damage.budget) {
|
|
718
|
+
return {
|
|
719
|
+
check: {
|
|
720
|
+
id: "logo",
|
|
721
|
+
passed: true,
|
|
722
|
+
message: `Logo covers ${percent}% of the code; error correction repairs it with room to spare`,
|
|
723
|
+
},
|
|
724
|
+
penalty: 0,
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
return {
|
|
728
|
+
check: {
|
|
729
|
+
id: "logo",
|
|
730
|
+
passed: false,
|
|
731
|
+
message: `Logo covers ${percent}% of the code and spoils ${damage.worst} codewords in one block, which repairs ${damage.correctable}`,
|
|
732
|
+
fix:
|
|
733
|
+
damage.level === "H"
|
|
734
|
+
? "Use a smaller logo"
|
|
735
|
+
: "Switch error correction to H or use a smaller logo",
|
|
736
|
+
},
|
|
737
|
+
penalty: damage.worst > damage.correctable ? 25 : 10,
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
function quietZoneCheck(props: QRProps): { check: ScanCheck; penalty: number } {
|
|
742
|
+
// A shaped code keeps at least QR_CIRCLE_QUIET_MIN before its decoration
|
|
743
|
+
const margin = isShapedCode(props.shape)
|
|
744
|
+
? circleQuietZone(props.margin ?? DEFAULT_MARGIN)
|
|
745
|
+
: (props.margin ?? DEFAULT_MARGIN);
|
|
746
|
+
const count = moduleCount(props).length + 2 * margin;
|
|
747
|
+
// A frame keeps a light gap around the code.
|
|
748
|
+
const modules =
|
|
749
|
+
margin +
|
|
750
|
+
(isFrameActive(props.frame) ? getFrameGapRatio(props.frame) * count : 0);
|
|
751
|
+
const rounded = Math.round(modules * 10) / 10;
|
|
752
|
+
if (modules >= 4) {
|
|
753
|
+
return {
|
|
754
|
+
check: {
|
|
755
|
+
id: "quiet-zone",
|
|
756
|
+
passed: true,
|
|
757
|
+
message: `Quiet zone of ${rounded} modules`,
|
|
758
|
+
},
|
|
759
|
+
penalty: 0,
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
if (modules >= 1.5) {
|
|
763
|
+
return {
|
|
764
|
+
check: {
|
|
765
|
+
id: "quiet-zone",
|
|
766
|
+
passed: true,
|
|
767
|
+
message: `Quiet zone of ${rounded} modules (4 is ideal)`,
|
|
768
|
+
},
|
|
769
|
+
penalty: 0,
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
return {
|
|
773
|
+
check: {
|
|
774
|
+
id: "quiet-zone",
|
|
775
|
+
passed: false,
|
|
776
|
+
message: "No quiet zone around the code",
|
|
777
|
+
fix: "Leave clear space (about 10% of the code width) around it wherever you place it, or add a frame",
|
|
778
|
+
},
|
|
779
|
+
penalty: 5,
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function eyeCheck(props: QRProps): { check: ScanCheck; penalty: number } {
|
|
784
|
+
// QRCodeSVG draws "gear" eyes when no pattern is given.
|
|
785
|
+
const pattern = props.cornerEyePattern ?? "gear";
|
|
786
|
+
if (pattern === "curly") {
|
|
787
|
+
return {
|
|
788
|
+
check: {
|
|
789
|
+
id: "eye-shape",
|
|
790
|
+
passed: false,
|
|
791
|
+
message: "Curly eyes fail strict decoders such as ZXing-based apps",
|
|
792
|
+
fix: "Pick square, rounded or gear eyes",
|
|
793
|
+
},
|
|
794
|
+
penalty: 40,
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
if (pattern === "circle") {
|
|
798
|
+
return {
|
|
799
|
+
check: {
|
|
800
|
+
id: "eye-shape",
|
|
801
|
+
passed: false,
|
|
802
|
+
message:
|
|
803
|
+
"Circle eyes only read in lenient decoders; many apps miss them",
|
|
804
|
+
fix: "Pick square, rounded or gear eyes",
|
|
805
|
+
},
|
|
806
|
+
penalty: 20,
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
return {
|
|
810
|
+
check: {
|
|
811
|
+
id: "eye-shape",
|
|
812
|
+
passed: true,
|
|
813
|
+
message: `No known decoder issues with ${pattern} eyes`,
|
|
814
|
+
},
|
|
815
|
+
penalty: 0,
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
function loadImage(src: string): Promise<HTMLImageElement> {
|
|
820
|
+
return new Promise((resolve, reject) => {
|
|
821
|
+
const img = new Image();
|
|
822
|
+
img.crossOrigin = "anonymous";
|
|
823
|
+
img.onload = () => resolve(img);
|
|
824
|
+
img.onerror = () => reject(new Error("Could not load image"));
|
|
825
|
+
img.src = src;
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// Stand-in for a logo that can't be loaded (e.g. CORS): an opaque block
|
|
830
|
+
// covers the same modules a real logo would.
|
|
831
|
+
const LOGO_PLACEHOLDER = `data:image/svg+xml,${encodeURIComponent(
|
|
832
|
+
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10" rx="2" fill="#808080"/></svg>'
|
|
833
|
+
)}`;
|
|
834
|
+
|
|
835
|
+
async function inlineLogo(props: QRProps): Promise<QRProps> {
|
|
836
|
+
const { imageSettings } = props;
|
|
837
|
+
if (!imageSettings || imageSettings.src.startsWith("data:")) {
|
|
838
|
+
return props;
|
|
839
|
+
}
|
|
840
|
+
let inlined = LOGO_PLACEHOLDER;
|
|
841
|
+
try {
|
|
842
|
+
const img = await loadImage(imageSettings.src);
|
|
843
|
+
const { canvas, ctx } = createCanvas(
|
|
844
|
+
img.naturalWidth || 256,
|
|
845
|
+
img.naturalHeight || 256
|
|
846
|
+
);
|
|
847
|
+
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
|
848
|
+
inlined = canvas.toDataURL("image/png");
|
|
849
|
+
} catch {
|
|
850
|
+
// Keep the placeholder
|
|
851
|
+
}
|
|
852
|
+
return { ...props, imageSettings: { ...imageSettings, src: inlined } };
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Image fills drawn from a data URL: an SVG drawn as an image can't load
|
|
857
|
+
* anything else, so other sources are redrawn on a canvas (or left out).
|
|
858
|
+
*/
|
|
859
|
+
async function inlineImagePaints(props: QRProps): Promise<QRProps> {
|
|
860
|
+
const inlined = new Map<string, string | null>();
|
|
861
|
+
for (const src of imageSources(props)) {
|
|
862
|
+
if (src.startsWith("data:")) {
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
try {
|
|
866
|
+
const img = await loadImage(src);
|
|
867
|
+
const { canvas, ctx } = createCanvas(
|
|
868
|
+
img.naturalWidth || 256,
|
|
869
|
+
img.naturalHeight || 256
|
|
870
|
+
);
|
|
871
|
+
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
|
872
|
+
inlined.set(src, canvas.toDataURL("image/png"));
|
|
873
|
+
canvas.remove();
|
|
874
|
+
} catch {
|
|
875
|
+
inlined.set(src, null);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (inlined.size === 0) {
|
|
879
|
+
return props;
|
|
880
|
+
}
|
|
881
|
+
const swap = (paint: ColorConfig | undefined): ColorConfig | undefined => {
|
|
882
|
+
if (typeof paint !== "object" || paint?.type !== "image") {
|
|
883
|
+
return paint;
|
|
884
|
+
}
|
|
885
|
+
const src = inlined.get(paint.src);
|
|
886
|
+
if (src === undefined) {
|
|
887
|
+
return paint;
|
|
888
|
+
}
|
|
889
|
+
return src ? { ...paint, src } : (paint.underlay ?? DEFAULT_FGCOLOR);
|
|
890
|
+
};
|
|
891
|
+
const eyeColors = props.eyeColors
|
|
892
|
+
? Object.fromEntries(
|
|
893
|
+
Object.entries(props.eyeColors).map(([position, eye]) => [
|
|
894
|
+
position,
|
|
895
|
+
eye && { outer: swap(eye.outer), inner: swap(eye.inner) },
|
|
896
|
+
])
|
|
897
|
+
)
|
|
898
|
+
: undefined;
|
|
899
|
+
return {
|
|
900
|
+
...props,
|
|
901
|
+
bgColor: swap(props.bgColor),
|
|
902
|
+
fgColor: swap(props.fgColor),
|
|
903
|
+
eyeColor: swap(props.eyeColor),
|
|
904
|
+
dotColor: swap(props.dotColor),
|
|
905
|
+
...(eyeColors && { eyeColors }),
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
type DrawArtwork = (codeWidth: number) => ImageData;
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* The score itself, shared by the browser and the pixel entry points:
|
|
913
|
+
* contrast, logo coverage vs error correction, quiet zone, eye shape and
|
|
914
|
+
* style-pair risk, plus decoding through the camera model at each size.
|
|
915
|
+
* `draw` returns the whole artwork (code and frame) with the code
|
|
916
|
+
* `codeWidth` px wide, on white.
|
|
917
|
+
*/
|
|
918
|
+
async function scoreArtwork(
|
|
919
|
+
props: QRProps,
|
|
920
|
+
draw: DrawArtwork,
|
|
921
|
+
sizes: number[],
|
|
922
|
+
signal?: AbortSignal,
|
|
923
|
+
imageTones?: ImageToneMap
|
|
924
|
+
): Promise<ScanScoreResult> {
|
|
925
|
+
const checks: ScanCheck[] = [];
|
|
926
|
+
let penalty = 0;
|
|
927
|
+
|
|
928
|
+
const contrast = contrastChecks(props, imageTones);
|
|
929
|
+
penalty += contrast.penalty;
|
|
930
|
+
const logo = logoCheck(props);
|
|
931
|
+
penalty += logo.penalty;
|
|
932
|
+
const quietZone = quietZoneCheck(props);
|
|
933
|
+
penalty += quietZone.penalty;
|
|
934
|
+
const eye = eyeCheck(props);
|
|
935
|
+
penalty += eye.penalty;
|
|
936
|
+
// Known-weak style pairs and centres (see scan-risk.ts); weak eyes on
|
|
937
|
+
// their own are already covered by the eye-shape check above.
|
|
938
|
+
const styleRisk = getStylePairRisk(props);
|
|
939
|
+
const pairRisk = styleRisk?.kind === "eye" ? null : styleRisk;
|
|
940
|
+
// Sharp-render pairs fail one strict decoder only (see scan-risk.ts): they
|
|
941
|
+
// show as a check with its fix but cost nothing until a phone test
|
|
942
|
+
// confirms them, so grades and the AI design loop don't change.
|
|
943
|
+
if (pairRisk && pairRisk.kind !== "sharp-dot-eye") {
|
|
944
|
+
penalty += 10;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
const jsQR = await loadDecoder();
|
|
948
|
+
throwIfAborted(signal);
|
|
949
|
+
|
|
950
|
+
const symbol = moduleCount(props).length;
|
|
951
|
+
const modules =
|
|
952
|
+
symbol +
|
|
953
|
+
2 * getLayoutMargin(symbol, props.margin ?? DEFAULT_MARGIN, props.shape);
|
|
954
|
+
const decodeChecks: ScanCheck[] = [];
|
|
955
|
+
let largestFails = false;
|
|
956
|
+
|
|
957
|
+
for (const [index, size] of sizes.entries()) {
|
|
958
|
+
await nextTick();
|
|
959
|
+
throwIfAborted(signal);
|
|
960
|
+
const state = decodeAtSize(jsQR, draw, size, modules, (result) =>
|
|
961
|
+
matches(result, props.value)
|
|
962
|
+
);
|
|
963
|
+
penalty += decodePenalty(index, sizes.length, state);
|
|
964
|
+
decodeChecks.push(decodeCheck(size, sizes, state));
|
|
965
|
+
if (index === sizes.length - 1 && state === "fail") {
|
|
966
|
+
largestFails = true;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
checks.push(...decodeChecks, ...contrast.checks);
|
|
971
|
+
if (logo.check) {
|
|
972
|
+
checks.push(logo.check);
|
|
973
|
+
}
|
|
974
|
+
checks.push(eye.check, quietZone.check);
|
|
975
|
+
if (pairRisk) {
|
|
976
|
+
checks.push({
|
|
977
|
+
id: "style-pair",
|
|
978
|
+
passed: false,
|
|
979
|
+
message: pairRisk.message,
|
|
980
|
+
fix: pairRisk.fix,
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
const fails = largestFails || contrast.fails;
|
|
985
|
+
let score = Math.max(0, Math.min(100, 100 - penalty));
|
|
986
|
+
if (fails) {
|
|
987
|
+
score = Math.min(score, 30);
|
|
988
|
+
}
|
|
989
|
+
return { score, grade: gradeFor(score, fails), checks };
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function testSizes(options: ScanScoreOptions): number[] {
|
|
993
|
+
return [...(options.sizes ?? SCAN_TEST_SIZES)]
|
|
994
|
+
.filter((size) => size > 0)
|
|
995
|
+
.sort((a, b) => a - b);
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/**
|
|
999
|
+
* Estimates how reliably a QR design scans (browser only). Renders the code
|
|
1000
|
+
* at several sizes with mild blur and contrast loss, decodes each with jsQR,
|
|
1001
|
+
* and combines that with contrast, logo coverage vs error correction, quiet
|
|
1002
|
+
* zone and eye-shape risk. jsQR is loaded on demand.
|
|
1003
|
+
*
|
|
1004
|
+
* This is a heuristic: real cameras, lighting and scanner apps vary.
|
|
1005
|
+
*/
|
|
1006
|
+
export async function getScanScore(
|
|
1007
|
+
props: QRProps,
|
|
1008
|
+
options: ScanScoreOptions = {}
|
|
1009
|
+
): Promise<ScanScoreResult> {
|
|
1010
|
+
assertBrowser();
|
|
1011
|
+
const { signal } = options;
|
|
1012
|
+
const sizes = testSizes(options);
|
|
1013
|
+
|
|
1014
|
+
const sourceProps = await inlineImagePaints(
|
|
1015
|
+
await inlineLogo(
|
|
1016
|
+
withQRSize({ ...props, size: props.size ?? DEFAULT_SIZE }, SOURCE_SIZE)
|
|
1017
|
+
)
|
|
1018
|
+
);
|
|
1019
|
+
throwIfAborted(signal);
|
|
1020
|
+
const imageTones: ImageToneMap = {};
|
|
1021
|
+
for (const src of imageSources(props)) {
|
|
1022
|
+
try {
|
|
1023
|
+
const tones = await getImageTones(src);
|
|
1024
|
+
if (tones) {
|
|
1025
|
+
imageTones[src] = tones;
|
|
1026
|
+
}
|
|
1027
|
+
} catch {
|
|
1028
|
+
// An image that won't load is judged by its underlay
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
throwIfAborted(signal);
|
|
1032
|
+
const svgUri = await getQRAsSVGDataUri(sourceProps);
|
|
1033
|
+
const img = await loadImage(svgUri);
|
|
1034
|
+
throwIfAborted(signal);
|
|
1035
|
+
|
|
1036
|
+
const artwork = getFrameDimensions(SOURCE_SIZE, props.frame);
|
|
1037
|
+
const drawArtwork = (codeWidth: number) => {
|
|
1038
|
+
const scale = codeWidth / SOURCE_SIZE;
|
|
1039
|
+
const width = artwork.width * scale;
|
|
1040
|
+
const height = artwork.height * scale;
|
|
1041
|
+
const pad = Math.max(8, Math.round(codeWidth * 0.12));
|
|
1042
|
+
const { canvas, ctx } = createCanvas(width + 2 * pad, height + 2 * pad);
|
|
1043
|
+
// Codes are scanned off paper or screens; test on white.
|
|
1044
|
+
ctx.fillStyle = "#ffffff";
|
|
1045
|
+
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
1046
|
+
ctx.drawImage(img, pad, pad, width, height);
|
|
1047
|
+
const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
1048
|
+
canvas.remove();
|
|
1049
|
+
return image;
|
|
1050
|
+
};
|
|
1051
|
+
return await scoreArtwork(props, drawArtwork, sizes, signal, imageTones);
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* Smallest code width (px) the artwork passed to `getScanScoreFromPixels`
|
|
1056
|
+
* should have: twice the largest default test size, so every test size is a
|
|
1057
|
+
* downscale, as it is in the browser.
|
|
1058
|
+
*/
|
|
1059
|
+
export const PIXEL_SCORE_MIN_CODE_WIDTH = SOURCE_SIZE;
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* `getScanScore` for servers and other places without a DOM: the same
|
|
1063
|
+
* checks, weights and camera model, decoding `pixels` instead of drawing the
|
|
1064
|
+
* SVG on a canvas. `pixels` is the whole artwork as `props` renders it (the
|
|
1065
|
+
* code plus its frame, if any), at any size with the code at least
|
|
1066
|
+
* `PIXEL_SCORE_MIN_CODE_WIDTH` px wide (rasterized with resvg, sharp or a
|
|
1067
|
+
* canvas). Transparent pixels count as white, like paper. Logos must already
|
|
1068
|
+
* be painted into the pixels; an opaque placeholder of the same size scores
|
|
1069
|
+
* the same.
|
|
1070
|
+
*/
|
|
1071
|
+
export async function getScanScoreFromPixels(
|
|
1072
|
+
props: QRProps,
|
|
1073
|
+
pixels: QRArtPixels,
|
|
1074
|
+
options: ScanScoreOptions = {}
|
|
1075
|
+
): Promise<ScanScoreResult> {
|
|
1076
|
+
const { width, height } = pixels;
|
|
1077
|
+
if (!(width > 0 && height > 0) || pixels.data.length < width * height * 4) {
|
|
1078
|
+
throw new Error("Pixels must be width × height × 4 RGBA bytes");
|
|
1079
|
+
}
|
|
1080
|
+
const sizes = testSizes(options);
|
|
1081
|
+
const size = props.size ?? DEFAULT_SIZE;
|
|
1082
|
+
const artwork = getFrameDimensions(size, props.frame);
|
|
1083
|
+
// Code width in the source pixels
|
|
1084
|
+
const sourceCodeWidth = (width * size) / artwork.width;
|
|
1085
|
+
const source = { data: onWhite(pixels), width, height };
|
|
1086
|
+
|
|
1087
|
+
const drawArtwork = (codeWidth: number) => {
|
|
1088
|
+
const art = resizePixels(source, codeWidth / sourceCodeWidth);
|
|
1089
|
+
const pad = Math.max(8, Math.round(codeWidth * 0.12));
|
|
1090
|
+
return padWhite(art, pad);
|
|
1091
|
+
};
|
|
1092
|
+
return await scoreArtwork(props, drawArtwork, sizes, options.signal);
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/** RGBA flattened onto white (opaque), as the browser draws on a white canvas. */
|
|
1096
|
+
function onWhite(pixels: QRArtPixels): Uint8ClampedArray {
|
|
1097
|
+
const { data, width, height } = pixels;
|
|
1098
|
+
const out = new Uint8ClampedArray(width * height * 4);
|
|
1099
|
+
for (let i = 0; i < width * height * 4; i += 4) {
|
|
1100
|
+
const alpha = (data[i + 3] as number) / 255;
|
|
1101
|
+
for (let c = 0; c < 3; c++) {
|
|
1102
|
+
out[i + c] = (data[i + c] as number) * alpha + 255 * (1 - alpha);
|
|
1103
|
+
}
|
|
1104
|
+
out[i + 3] = 255;
|
|
1105
|
+
}
|
|
1106
|
+
return out;
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/** `image` centred on a white border `pad` px wide. */
|
|
1110
|
+
function padWhite(image: ImageData, pad: number): ImageData {
|
|
1111
|
+
const width = image.width + 2 * pad;
|
|
1112
|
+
const height = image.height + 2 * pad;
|
|
1113
|
+
const out = new Uint8ClampedArray(width * height * 4).fill(255);
|
|
1114
|
+
for (let y = 0; y < image.height; y++) {
|
|
1115
|
+
out.set(
|
|
1116
|
+
image.data.subarray(y * image.width * 4, (y + 1) * image.width * 4),
|
|
1117
|
+
((y + pad) * width + pad) * 4
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
return { data: out, width, height, colorSpace: "srgb" } as ImageData;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
// ── Images ─────────────────────────────────────────────────────────────────
|
|
1124
|
+
|
|
1125
|
+
interface Point {
|
|
1126
|
+
x: number;
|
|
1127
|
+
y: number;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y);
|
|
1131
|
+
|
|
1132
|
+
function lumaAt(data: Uint8ClampedArray, index: number) {
|
|
1133
|
+
return (
|
|
1134
|
+
0.299 * (data[index] as number) +
|
|
1135
|
+
0.587 * (data[index + 1] as number) +
|
|
1136
|
+
0.114 * (data[index + 2] as number)
|
|
1137
|
+
);
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
/** Otsu threshold over the luma histogram of a region. */
|
|
1141
|
+
function otsu(histogram: number[], total: number): number {
|
|
1142
|
+
let sum = 0;
|
|
1143
|
+
for (let i = 0; i < 256; i++) {
|
|
1144
|
+
sum += i * (histogram[i] as number);
|
|
1145
|
+
}
|
|
1146
|
+
let sumBackground = 0;
|
|
1147
|
+
let weightBackground = 0;
|
|
1148
|
+
let best = 0;
|
|
1149
|
+
let threshold = 128;
|
|
1150
|
+
for (let i = 0; i < 256; i++) {
|
|
1151
|
+
weightBackground += histogram[i] as number;
|
|
1152
|
+
if (weightBackground === 0) {
|
|
1153
|
+
continue;
|
|
1154
|
+
}
|
|
1155
|
+
const weightForeground = total - weightBackground;
|
|
1156
|
+
if (weightForeground === 0) {
|
|
1157
|
+
break;
|
|
1158
|
+
}
|
|
1159
|
+
sumBackground += i * (histogram[i] as number);
|
|
1160
|
+
const meanBackground = sumBackground / weightBackground;
|
|
1161
|
+
const meanForeground = (sum - sumBackground) / weightForeground;
|
|
1162
|
+
const between =
|
|
1163
|
+
weightBackground *
|
|
1164
|
+
weightForeground *
|
|
1165
|
+
(meanBackground - meanForeground) ** 2;
|
|
1166
|
+
if (between > best) {
|
|
1167
|
+
best = between;
|
|
1168
|
+
threshold = i;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
return threshold;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
async function imageFromSource(
|
|
1175
|
+
source: HTMLImageElement | Blob
|
|
1176
|
+
): Promise<HTMLImageElement> {
|
|
1177
|
+
if (!(source instanceof Blob)) {
|
|
1178
|
+
if (!source.complete) {
|
|
1179
|
+
await new Promise((resolve) => {
|
|
1180
|
+
source.addEventListener("load", resolve, { once: true });
|
|
1181
|
+
source.addEventListener("error", resolve, { once: true });
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
return source;
|
|
1185
|
+
}
|
|
1186
|
+
const url = URL.createObjectURL(source);
|
|
1187
|
+
try {
|
|
1188
|
+
const img = await loadImage(url);
|
|
1189
|
+
await img.decode?.().catch(() => undefined);
|
|
1190
|
+
return img;
|
|
1191
|
+
} finally {
|
|
1192
|
+
// The decoded image stays usable after the URL is revoked.
|
|
1193
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
/**
|
|
1198
|
+
* Scores an existing QR code image (browser only, nothing is uploaded):
|
|
1199
|
+
* finds and decodes the code, then checks it still decodes when shrunk and
|
|
1200
|
+
* blurred, its contrast, polarity, quiet zone and the image resolution.
|
|
1201
|
+
*/
|
|
1202
|
+
export async function getImageScanScore(
|
|
1203
|
+
source: HTMLImageElement | Blob,
|
|
1204
|
+
options: ScanScoreOptions = {}
|
|
1205
|
+
): Promise<ImageScanScoreResult> {
|
|
1206
|
+
assertBrowser();
|
|
1207
|
+
const { signal } = options;
|
|
1208
|
+
const sizes = [...(options.sizes ?? SCAN_TEST_SIZES)]
|
|
1209
|
+
.filter((size) => size > 0)
|
|
1210
|
+
.sort((a, b) => a - b);
|
|
1211
|
+
const jsQR = await loadDecoder();
|
|
1212
|
+
const img = await imageFromSource(source);
|
|
1213
|
+
throwIfAborted(signal);
|
|
1214
|
+
|
|
1215
|
+
const naturalWidth = img.naturalWidth || img.width;
|
|
1216
|
+
const naturalHeight = img.naturalHeight || img.height;
|
|
1217
|
+
if (!(naturalWidth && naturalHeight)) {
|
|
1218
|
+
throw new Error("Could not read this image");
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
const fit = Math.min(1, 1600 / Math.max(naturalWidth, naturalHeight));
|
|
1222
|
+
const { canvas, ctx } = createCanvas(naturalWidth * fit, naturalHeight * fit);
|
|
1223
|
+
ctx.fillStyle = "#ffffff";
|
|
1224
|
+
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
1225
|
+
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
|
1226
|
+
const full = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
1227
|
+
const located = jsQR(full.data, full.width, full.height);
|
|
1228
|
+
throwIfAborted(signal);
|
|
1229
|
+
|
|
1230
|
+
if (!located) {
|
|
1231
|
+
// Fall back to the library's crop-and-retry detection for the content.
|
|
1232
|
+
const detected = await handleImageLoad(img, 0, false);
|
|
1233
|
+
canvas.remove();
|
|
1234
|
+
if (typeof detected !== "string" || detected === "NO_QR") {
|
|
1235
|
+
return {
|
|
1236
|
+
data: null,
|
|
1237
|
+
version: null,
|
|
1238
|
+
score: 0,
|
|
1239
|
+
grade: "fails",
|
|
1240
|
+
checks: [
|
|
1241
|
+
{
|
|
1242
|
+
id: "decode",
|
|
1243
|
+
passed: false,
|
|
1244
|
+
message: "No QR code found in this image",
|
|
1245
|
+
fix: "Try a sharper, well-lit, straight-on photo or a screenshot",
|
|
1246
|
+
},
|
|
1247
|
+
],
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
return {
|
|
1251
|
+
data: detected,
|
|
1252
|
+
version: null,
|
|
1253
|
+
score: 55,
|
|
1254
|
+
grade: "risky",
|
|
1255
|
+
checks: [
|
|
1256
|
+
{
|
|
1257
|
+
id: "decode",
|
|
1258
|
+
passed: false,
|
|
1259
|
+
message:
|
|
1260
|
+
"Decoded only after cropping; the code is small or hard to find in this image",
|
|
1261
|
+
fix: "Make the code bigger relative to its surroundings",
|
|
1262
|
+
},
|
|
1263
|
+
],
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
const { location, version } = located;
|
|
1268
|
+
const dimension = 17 + 4 * version;
|
|
1269
|
+
const codeWidth =
|
|
1270
|
+
(distance(location.topLeftCorner, location.topRightCorner) +
|
|
1271
|
+
distance(location.bottomLeftCorner, location.bottomRightCorner) +
|
|
1272
|
+
distance(location.topLeftCorner, location.bottomLeftCorner) +
|
|
1273
|
+
distance(location.topRightCorner, location.bottomRightCorner)) /
|
|
1274
|
+
4;
|
|
1275
|
+
const modulePx = codeWidth / dimension;
|
|
1276
|
+
const corners = [
|
|
1277
|
+
location.topLeftCorner,
|
|
1278
|
+
location.topRightCorner,
|
|
1279
|
+
location.bottomRightCorner,
|
|
1280
|
+
location.bottomLeftCorner,
|
|
1281
|
+
];
|
|
1282
|
+
const minX = Math.max(0, Math.floor(Math.min(...corners.map((p) => p.x))));
|
|
1283
|
+
const maxX = Math.min(
|
|
1284
|
+
full.width,
|
|
1285
|
+
Math.ceil(Math.max(...corners.map((p) => p.x)))
|
|
1286
|
+
);
|
|
1287
|
+
const minY = Math.max(0, Math.floor(Math.min(...corners.map((p) => p.y))));
|
|
1288
|
+
const maxY = Math.min(
|
|
1289
|
+
full.height,
|
|
1290
|
+
Math.ceil(Math.max(...corners.map((p) => p.y)))
|
|
1291
|
+
);
|
|
1292
|
+
|
|
1293
|
+
const checks: ScanCheck[] = [];
|
|
1294
|
+
let penalty = 0;
|
|
1295
|
+
|
|
1296
|
+
// Contrast: split the code's pixels into dark and light with Otsu.
|
|
1297
|
+
const histogram = new Array<number>(256).fill(0);
|
|
1298
|
+
let total = 0;
|
|
1299
|
+
for (let y = minY; y < maxY; y++) {
|
|
1300
|
+
for (let x = minX; x < maxX; x++) {
|
|
1301
|
+
const luma = Math.round(lumaAt(full.data, (y * full.width + x) * 4));
|
|
1302
|
+
histogram[luma] = (histogram[luma] as number) + 1;
|
|
1303
|
+
total++;
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
const threshold = otsu(histogram, total);
|
|
1307
|
+
const sums = { dark: [0, 0, 0, 0], light: [0, 0, 0, 0] };
|
|
1308
|
+
for (let y = minY; y < maxY; y++) {
|
|
1309
|
+
for (let x = minX; x < maxX; x++) {
|
|
1310
|
+
const i = (y * full.width + x) * 4;
|
|
1311
|
+
const bucket = lumaAt(full.data, i) <= threshold ? sums.dark : sums.light;
|
|
1312
|
+
bucket[0] = (bucket[0] as number) + (full.data[i] as number);
|
|
1313
|
+
bucket[1] = (bucket[1] as number) + (full.data[i + 1] as number);
|
|
1314
|
+
bucket[2] = (bucket[2] as number) + (full.data[i + 2] as number);
|
|
1315
|
+
bucket[3] = (bucket[3] as number) + 1;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
const mean = (bucket: number[]) => {
|
|
1319
|
+
const count = Math.max(bucket[3] as number, 1);
|
|
1320
|
+
return getLuminance(
|
|
1321
|
+
(bucket[0] as number) / count,
|
|
1322
|
+
(bucket[1] as number) / count,
|
|
1323
|
+
(bucket[2] as number) / count
|
|
1324
|
+
);
|
|
1325
|
+
};
|
|
1326
|
+
const darkLum = mean(sums.dark);
|
|
1327
|
+
const lightLum = mean(sums.light);
|
|
1328
|
+
const contrast = ratioOf(darkLum, lightLum);
|
|
1329
|
+
const contrastRounded = Math.round(contrast * 10) / 10;
|
|
1330
|
+
if (contrast >= 4.5) {
|
|
1331
|
+
checks.push({
|
|
1332
|
+
id: "contrast",
|
|
1333
|
+
passed: true,
|
|
1334
|
+
message: `Contrast ${contrastRounded}:1 in the image`,
|
|
1335
|
+
});
|
|
1336
|
+
} else {
|
|
1337
|
+
penalty += contrast < 2 ? 30 : 10;
|
|
1338
|
+
checks.push({
|
|
1339
|
+
id: "contrast",
|
|
1340
|
+
passed: false,
|
|
1341
|
+
message: `Low contrast in the image (${contrastRounded}:1)`,
|
|
1342
|
+
fix: "Use a darker code on a lighter background, or better lighting for photos",
|
|
1343
|
+
});
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
// Polarity: finder pattern centers are dark in a normal code.
|
|
1347
|
+
const finderLuma = [
|
|
1348
|
+
location.topLeftFinderPattern,
|
|
1349
|
+
location.topRightFinderPattern,
|
|
1350
|
+
location.bottomLeftFinderPattern,
|
|
1351
|
+
].map((point) => {
|
|
1352
|
+
const x = Math.min(full.width - 1, Math.max(0, Math.round(point.x)));
|
|
1353
|
+
const y = Math.min(full.height - 1, Math.max(0, Math.round(point.y)));
|
|
1354
|
+
return lumaAt(full.data, (y * full.width + x) * 4);
|
|
1355
|
+
});
|
|
1356
|
+
const inverted = finderLuma.filter((luma) => luma > threshold).length >= 2;
|
|
1357
|
+
if (inverted) {
|
|
1358
|
+
penalty += 10;
|
|
1359
|
+
checks.push({
|
|
1360
|
+
id: "polarity",
|
|
1361
|
+
passed: false,
|
|
1362
|
+
message:
|
|
1363
|
+
"Light code on a dark background; some scanner apps can't read it",
|
|
1364
|
+
fix: "Use dark modules on a light background",
|
|
1365
|
+
});
|
|
1366
|
+
} else {
|
|
1367
|
+
checks.push({
|
|
1368
|
+
id: "polarity",
|
|
1369
|
+
passed: true,
|
|
1370
|
+
message: "Dark code on a light background",
|
|
1371
|
+
});
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
// Quiet zone: a 2-module ring around the code should be clear.
|
|
1375
|
+
const ring = Math.max(2, Math.round(modulePx * 2));
|
|
1376
|
+
const ringBox = {
|
|
1377
|
+
minX: minX - ring,
|
|
1378
|
+
maxX: maxX + ring,
|
|
1379
|
+
minY: minY - ring,
|
|
1380
|
+
maxY: maxY + ring,
|
|
1381
|
+
};
|
|
1382
|
+
const clipped =
|
|
1383
|
+
ringBox.minX < 0 ||
|
|
1384
|
+
ringBox.minY < 0 ||
|
|
1385
|
+
ringBox.maxX > full.width ||
|
|
1386
|
+
ringBox.maxY > full.height;
|
|
1387
|
+
if (clipped) {
|
|
1388
|
+
checks.push({
|
|
1389
|
+
id: "quiet-zone",
|
|
1390
|
+
passed: true,
|
|
1391
|
+
skipped: true,
|
|
1392
|
+
message: "The image is cropped too tight to check the quiet zone",
|
|
1393
|
+
});
|
|
1394
|
+
} else {
|
|
1395
|
+
let busy = 0;
|
|
1396
|
+
let ringTotal = 0;
|
|
1397
|
+
for (let y = ringBox.minY; y < ringBox.maxY; y++) {
|
|
1398
|
+
for (let x = ringBox.minX; x < ringBox.maxX; x++) {
|
|
1399
|
+
if (x >= minX && x < maxX && y >= minY && y < maxY) {
|
|
1400
|
+
continue;
|
|
1401
|
+
}
|
|
1402
|
+
const luma = lumaAt(full.data, (y * full.width + x) * 4);
|
|
1403
|
+
if (inverted ? luma > threshold : luma <= threshold) {
|
|
1404
|
+
busy++;
|
|
1405
|
+
}
|
|
1406
|
+
ringTotal++;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
// Rotated codes put some module pixels in the ring, so allow a little.
|
|
1410
|
+
if (busy / Math.max(ringTotal, 1) > 0.12) {
|
|
1411
|
+
penalty += 10;
|
|
1412
|
+
checks.push({
|
|
1413
|
+
id: "quiet-zone",
|
|
1414
|
+
passed: false,
|
|
1415
|
+
message: "Something dark touches the code; the quiet zone isn't clear",
|
|
1416
|
+
fix: "Leave clear space (about 4 modules) around the code",
|
|
1417
|
+
});
|
|
1418
|
+
} else {
|
|
1419
|
+
checks.push({
|
|
1420
|
+
id: "quiet-zone",
|
|
1421
|
+
passed: true,
|
|
1422
|
+
message: "Clear space around the code",
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
if (modulePx < 2) {
|
|
1428
|
+
checks.push({
|
|
1429
|
+
id: "resolution",
|
|
1430
|
+
passed: false,
|
|
1431
|
+
message: `Low resolution: about ${Math.round(modulePx * 10) / 10} px per module`,
|
|
1432
|
+
fix: "Use a larger image, or export the code at a bigger size",
|
|
1433
|
+
});
|
|
1434
|
+
} else {
|
|
1435
|
+
checks.push({
|
|
1436
|
+
id: "resolution",
|
|
1437
|
+
passed: true,
|
|
1438
|
+
message: `About ${Math.round(modulePx)} px per module`,
|
|
1439
|
+
});
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
// Decode the cropped code shrunk to each test size, with mild blur.
|
|
1443
|
+
const margin = Math.round(modulePx * 4);
|
|
1444
|
+
const cropX = Math.max(0, minX - margin);
|
|
1445
|
+
const cropY = Math.max(0, minY - margin);
|
|
1446
|
+
const cropWidth = Math.min(full.width, maxX + margin) - cropX;
|
|
1447
|
+
const cropHeight = Math.min(full.height, maxY + margin) - cropY;
|
|
1448
|
+
const drawCrop = (targetWidth: number) => {
|
|
1449
|
+
const scale = targetWidth / codeWidth;
|
|
1450
|
+
const test = createCanvas(cropWidth * scale, cropHeight * scale);
|
|
1451
|
+
test.ctx.drawImage(
|
|
1452
|
+
canvas,
|
|
1453
|
+
cropX,
|
|
1454
|
+
cropY,
|
|
1455
|
+
cropWidth,
|
|
1456
|
+
cropHeight,
|
|
1457
|
+
0,
|
|
1458
|
+
0,
|
|
1459
|
+
test.canvas.width,
|
|
1460
|
+
test.canvas.height
|
|
1461
|
+
);
|
|
1462
|
+
const image = test.ctx.getImageData(
|
|
1463
|
+
0,
|
|
1464
|
+
0,
|
|
1465
|
+
test.canvas.width,
|
|
1466
|
+
test.canvas.height
|
|
1467
|
+
);
|
|
1468
|
+
test.canvas.remove();
|
|
1469
|
+
return image;
|
|
1470
|
+
};
|
|
1471
|
+
const decodeChecks: ScanCheck[] = [];
|
|
1472
|
+
let largestFails = false;
|
|
1473
|
+
for (const [index, size] of sizes.entries()) {
|
|
1474
|
+
await nextTick();
|
|
1475
|
+
throwIfAborted(signal);
|
|
1476
|
+
const state = decodeAtSize(
|
|
1477
|
+
jsQR,
|
|
1478
|
+
drawCrop,
|
|
1479
|
+
size,
|
|
1480
|
+
dimension,
|
|
1481
|
+
(result) => result?.data === located.data
|
|
1482
|
+
);
|
|
1483
|
+
penalty += decodePenalty(index, sizes.length, state);
|
|
1484
|
+
decodeChecks.push(decodeCheck(size, sizes, state));
|
|
1485
|
+
if (index === sizes.length - 1 && state === "fail") {
|
|
1486
|
+
largestFails = true;
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
canvas.remove();
|
|
1490
|
+
|
|
1491
|
+
let score = Math.max(0, Math.min(100, 100 - penalty));
|
|
1492
|
+
if (largestFails) {
|
|
1493
|
+
score = Math.min(score, 30);
|
|
1494
|
+
}
|
|
1495
|
+
return {
|
|
1496
|
+
data: located.data,
|
|
1497
|
+
version,
|
|
1498
|
+
score,
|
|
1499
|
+
grade: gradeFor(score, largestFails),
|
|
1500
|
+
checks: [...decodeChecks, ...checks],
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// ── Raw pixels (Node and browsers) ─────────────────────────────────────────
|
|
1505
|
+
|
|
1506
|
+
export interface PixelScanResult {
|
|
1507
|
+
/** What the pixels decode to as they are, or null when no code was found */
|
|
1508
|
+
data: string | null;
|
|
1509
|
+
/** QR version of the code that was found, or null */
|
|
1510
|
+
version: number | null;
|
|
1511
|
+
/**
|
|
1512
|
+
* True when the pixels decode to `expected` as they are and, at every
|
|
1513
|
+
* check size, through the phone-camera model (two of three attempts)
|
|
1514
|
+
*/
|
|
1515
|
+
passed: boolean;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/** Code widths (px) `scanQRPixels` checks through the camera model. */
|
|
1519
|
+
export const PIXEL_SCAN_SIZES = [320] as const;
|
|
1520
|
+
|
|
1521
|
+
/** Area-average resize of RGBA pixels by `scale` (at most 1). */
|
|
1522
|
+
function resizePixels(
|
|
1523
|
+
source: { data: Uint8ClampedArray; width: number; height: number },
|
|
1524
|
+
scale: number
|
|
1525
|
+
): ImageData {
|
|
1526
|
+
const factor = Math.min(1, scale);
|
|
1527
|
+
const width = Math.max(1, Math.round(source.width * factor));
|
|
1528
|
+
const height = Math.max(1, Math.round(source.height * factor));
|
|
1529
|
+
const out = new Uint8ClampedArray(width * height * 4);
|
|
1530
|
+
const stepX = source.width / width;
|
|
1531
|
+
const stepY = source.height / height;
|
|
1532
|
+
for (let y = 0; y < height; y++) {
|
|
1533
|
+
const y0 = Math.floor(y * stepY);
|
|
1534
|
+
const y1 = Math.max(
|
|
1535
|
+
y0 + 1,
|
|
1536
|
+
Math.min(source.height, Math.floor((y + 1) * stepY))
|
|
1537
|
+
);
|
|
1538
|
+
for (let x = 0; x < width; x++) {
|
|
1539
|
+
const x0 = Math.floor(x * stepX);
|
|
1540
|
+
const x1 = Math.max(
|
|
1541
|
+
x0 + 1,
|
|
1542
|
+
Math.min(source.width, Math.floor((x + 1) * stepX))
|
|
1543
|
+
);
|
|
1544
|
+
const sums = [0, 0, 0, 0];
|
|
1545
|
+
for (let sy = y0; sy < y1; sy++) {
|
|
1546
|
+
for (let sx = x0; sx < x1; sx++) {
|
|
1547
|
+
const i = (sy * source.width + sx) * 4;
|
|
1548
|
+
for (let c = 0; c < 4; c++) {
|
|
1549
|
+
sums[c] = (sums[c] as number) + (source.data[i + c] as number);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
const count = (y1 - y0) * (x1 - x0);
|
|
1554
|
+
const o = (y * width + x) * 4;
|
|
1555
|
+
for (let c = 0; c < 4; c++) {
|
|
1556
|
+
out[o + c] = (sums[c] as number) / count;
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
return { data: out, width, height, colorSpace: "srgb" } as ImageData;
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
function decodedText(result: JsQRResult): string {
|
|
1564
|
+
try {
|
|
1565
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(
|
|
1566
|
+
Uint8Array.from(result.binaryData)
|
|
1567
|
+
);
|
|
1568
|
+
} catch {
|
|
1569
|
+
return result.data;
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
/**
|
|
1574
|
+
* Checks that raw RGBA pixels (from `decodePNGPixels`, `sharp().raw()` or a
|
|
1575
|
+
* canvas) hold a QR code that decodes to `expected`: as they are, and through
|
|
1576
|
+
* the phone-camera model (blur and contrast loss) with the code shrunk to each
|
|
1577
|
+
* of `sizes` px. Needs no DOM, so it runs in Node. Light-on-dark codes fail,
|
|
1578
|
+
* since many scanner apps can't read them.
|
|
1579
|
+
*/
|
|
1580
|
+
export async function scanQRPixels(
|
|
1581
|
+
pixels: QRArtPixels,
|
|
1582
|
+
expected: string,
|
|
1583
|
+
options: { sizes?: readonly number[] } = {}
|
|
1584
|
+
): Promise<PixelScanResult> {
|
|
1585
|
+
const { width, height } = pixels;
|
|
1586
|
+
if (!(width > 0 && height > 0) || pixels.data.length < width * height * 4) {
|
|
1587
|
+
throw new Error("Pixels must be width × height × 4 RGBA bytes");
|
|
1588
|
+
}
|
|
1589
|
+
const jsQR = await loadDecoder();
|
|
1590
|
+
const source = {
|
|
1591
|
+
data:
|
|
1592
|
+
pixels.data instanceof Uint8ClampedArray
|
|
1593
|
+
? pixels.data
|
|
1594
|
+
: Uint8ClampedArray.from(pixels.data),
|
|
1595
|
+
width,
|
|
1596
|
+
height,
|
|
1597
|
+
};
|
|
1598
|
+
const located = jsQR(source.data, width, height, {
|
|
1599
|
+
inversionAttempts: "dontInvert",
|
|
1600
|
+
});
|
|
1601
|
+
if (!located) {
|
|
1602
|
+
return { data: null, version: null, passed: false };
|
|
1603
|
+
}
|
|
1604
|
+
const data = decodedText(located);
|
|
1605
|
+
const { version, location } = located;
|
|
1606
|
+
if (!matches(located, expected)) {
|
|
1607
|
+
return { data, version, passed: false };
|
|
1608
|
+
}
|
|
1609
|
+
const dimension = 17 + 4 * version;
|
|
1610
|
+
const codeWidth =
|
|
1611
|
+
(distance(location.topLeftCorner, location.topRightCorner) +
|
|
1612
|
+
distance(location.bottomLeftCorner, location.bottomRightCorner) +
|
|
1613
|
+
distance(location.topLeftCorner, location.bottomLeftCorner) +
|
|
1614
|
+
distance(location.topRightCorner, location.bottomRightCorner)) /
|
|
1615
|
+
4;
|
|
1616
|
+
for (const size of options.sizes ?? PIXEL_SCAN_SIZES) {
|
|
1617
|
+
const state = decodeAtSize(
|
|
1618
|
+
jsQR,
|
|
1619
|
+
(target) => resizePixels(source, target / codeWidth),
|
|
1620
|
+
size,
|
|
1621
|
+
dimension,
|
|
1622
|
+
(result) => matches(result, expected)
|
|
1623
|
+
);
|
|
1624
|
+
if (state !== "pass") {
|
|
1625
|
+
return { data, version, passed: false };
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
return { data, version, passed: true };
|
|
1629
|
+
}
|