forked from cozmo/jsQR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
83 lines (69 loc) · 2.59 KB
/
index.ts
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
import {binarize} from "./binarizer";
import {BitMatrix} from "./BitMatrix";
import {Chunks} from "./decoder/decodeData";
import {decode} from "./decoder/decoder";
import {extract} from "./extractor";
import {locate, Point} from "./locator";
export interface QRCode {
binaryData: number[];
data: string;
chunks: Chunks;
location: {
topRightCorner: Point;
topLeftCorner: Point;
bottomRightCorner: Point;
bottomLeftCorner: Point;
topRightFinderPattern: Point;
topLeftFinderPattern: Point;
bottomLeftFinderPattern: Point;
bottomRightAlignmentPattern?: Point;
};
}
function scan(matrix: BitMatrix): QRCode | null {
const location = locate(matrix);
if (!location) {
return null;
}
const extracted = extract(matrix, location);
const decoded = decode(extracted.matrix);
if (!decoded) {
return null;
}
return {
binaryData: decoded.bytes,
data: decoded.text,
chunks: decoded.chunks,
location: {
topRightCorner: extracted.mappingFunction(location.dimension, 0),
topLeftCorner: extracted.mappingFunction(0, 0),
bottomRightCorner: extracted.mappingFunction(location.dimension, location.dimension),
bottomLeftCorner: extracted.mappingFunction(0, location.dimension),
topRightFinderPattern: location.topRight,
topLeftFinderPattern: location.topLeft,
bottomLeftFinderPattern: location.bottomLeft,
bottomRightAlignmentPattern: location.alignmentPattern,
},
};
}
export interface Options {
inversionAttempts?: "dontInvert" | "onlyInvert" | "attemptBoth" | "invertFirst";
}
const defaultOptions: Options = {
inversionAttempts: "attemptBoth",
};
function jsQR(data: Uint8ClampedArray, width: number, height: number, providedOptions: Options = {}): QRCode | null {
const options = defaultOptions;
Object.keys(options || {}).forEach(opt => { // Sad implementation of Object.assign since we target es5 not es6
(options as any)[opt] = (providedOptions as any)[opt] || (options as any)[opt];
});
const shouldInvert = options.inversionAttempts === "attemptBoth" || options.inversionAttempts === "invertFirst";
const tryInvertedFirst = options.inversionAttempts === "onlyInvert" || options.inversionAttempts === "invertFirst";
const {binarized, inverted} = binarize(data, width, height, shouldInvert);
let result = scan(tryInvertedFirst ? inverted : binarized);
if (!result && (options.inversionAttempts === "attemptBoth" || options.inversionAttempts === "invertFirst")) {
result = scan(tryInvertedFirst ? binarized : inverted);
}
return result;
}
(jsQR as any).default = jsQR;
export default jsQR;