@lexion-rte/image-tools 0.0.0-stage → 0.1.0

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/src/rtf.ts ADDED
@@ -0,0 +1,182 @@
1
+ import { sniffImageType } from "./bytes.js";
2
+ import { DEFAULT_MAX_IMAGE_BYTES } from "./data-url.js";
3
+
4
+ /** A PNG or JPEG picture found in RTF. */
5
+ export interface RtfImage {
6
+ readonly bytes: Uint8Array;
7
+ readonly type: "image/png" | "image/jpeg";
8
+ /** Display size in CSS px (`\picwgoal` × `\picscalex`), when the RTF gives one. */
9
+ readonly width: number | null;
10
+ readonly height: number | null;
11
+ }
12
+
13
+ export interface ExtractRtfImagesOptions {
14
+ /** Pictures larger than this, in bytes, are skipped. Default 5 MB. */
15
+ readonly maxBytes?: number;
16
+ }
17
+
18
+ interface Picture {
19
+ type: "image/png" | "image/jpeg" | null;
20
+ hex: string[];
21
+ binary: number[];
22
+ goalWidth: number | null;
23
+ goalHeight: number | null;
24
+ scaleX: number;
25
+ scaleY: number;
26
+ }
27
+
28
+ interface Group {
29
+ /** Inside `\nonshppict` (a duplicate for old readers) or another ignored destination. */
30
+ readonly skip: boolean;
31
+ picture: Picture | null;
32
+ ignoreNext: boolean;
33
+ }
34
+
35
+ const twipsToPx = (twips: number | null, scale: number): number | null =>
36
+ twips && twips > 0 ? Math.round(((twips * scale) / 100 / 15) * 100) / 100 : null;
37
+
38
+ const hexToBytes = (hex: string): Uint8Array => {
39
+ const bytes = new Uint8Array(hex.length >> 1);
40
+ for (let index = 0; index < bytes.length; index += 1) {
41
+ bytes[index] = parseInt(hex.slice(index * 2, index * 2 + 2), 16);
42
+ }
43
+ return bytes;
44
+ };
45
+
46
+ const isHexDigit = (code: number): boolean =>
47
+ (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102);
48
+
49
+ /**
50
+ * PNG and JPEG pictures (`\pict` with `\pngblip` / `\jpegblip`) in RTF, such as Word puts on
51
+ * the clipboard, in document order. `\nonshppict` copies (duplicates for old readers) are
52
+ * skipped, and so are WMF/EMF/other formats, pictures whose bytes do not match their declared
53
+ * format, and pictures over `maxBytes`. Never throws on malformed RTF.
54
+ */
55
+ export const extractRtfImages = (
56
+ rtf: string,
57
+ options: ExtractRtfImagesOptions = {}
58
+ ): RtfImage[] => {
59
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
60
+ const images: RtfImage[] = [];
61
+ const stack: Group[] = [{ skip: false, picture: null, ignoreNext: false }];
62
+ const current = (): Group => stack[stack.length - 1] as Group;
63
+
64
+ const finish = (picture: Picture): void => {
65
+ const hex = picture.hex.join("");
66
+ const bytes =
67
+ picture.binary.length > 0
68
+ ? new Uint8Array(picture.binary)
69
+ : hexToBytes(hex.length % 2 === 0 ? hex : hex.slice(0, -1));
70
+ if (!picture.type || bytes.length === 0 || bytes.length > maxBytes) {
71
+ return;
72
+ }
73
+ if (sniffImageType(bytes) !== picture.type) {
74
+ return;
75
+ }
76
+ images.push({
77
+ bytes,
78
+ type: picture.type,
79
+ width: twipsToPx(picture.goalWidth, picture.scaleX),
80
+ height: twipsToPx(picture.goalHeight, picture.scaleY)
81
+ });
82
+ };
83
+
84
+ let index = 0;
85
+ while (index < rtf.length) {
86
+ const character = rtf[index] as string;
87
+ if (character === "{") {
88
+ stack.push({ skip: current().skip, picture: null, ignoreNext: false });
89
+ index += 1;
90
+ continue;
91
+ }
92
+ if (character === "}") {
93
+ const group = stack.length > 1 ? stack.pop() : undefined;
94
+ if (group?.picture && !group.skip) {
95
+ finish(group.picture);
96
+ }
97
+ index += 1;
98
+ continue;
99
+ }
100
+ if (character === "\\") {
101
+ const word = /^\\([a-zA-Z]{1,32})(-?\d{1,10})? ?/.exec(rtf.slice(index, index + 45));
102
+ if (!word) {
103
+ // Control symbol: `\'hh` (a hex-escaped character), `\*`, `\\`, `\{`…
104
+ const next = rtf[index + 1];
105
+ if (next === "*") {
106
+ current().ignoreNext = true;
107
+ }
108
+ index += next === "'" ? 4 : 2;
109
+ continue;
110
+ }
111
+ index += word[0].length;
112
+ const name = word[1] as string;
113
+ const parameter = word[2] === undefined ? null : Number(word[2]);
114
+ const group = current();
115
+ const ignored = group.ignoreNext;
116
+ group.ignoreNext = false;
117
+ if (name === "nonshppict") {
118
+ stack[stack.length - 1] = { ...group, skip: true };
119
+ continue;
120
+ }
121
+ if (name === "pict" && !group.skip) {
122
+ group.picture = {
123
+ type: null,
124
+ hex: [],
125
+ binary: [],
126
+ goalWidth: null,
127
+ goalHeight: null,
128
+ scaleX: 100,
129
+ scaleY: 100
130
+ };
131
+ continue;
132
+ }
133
+ if (ignored && !group.picture && name !== "shppict") {
134
+ // An unknown `{\*\destination …}`: its text is not content.
135
+ stack[stack.length - 1] = { ...group, skip: true };
136
+ continue;
137
+ }
138
+ const picture = group.picture;
139
+ if (!picture) {
140
+ continue;
141
+ }
142
+ if (name === "pngblip") {
143
+ picture.type = "image/png";
144
+ } else if (name === "jpegblip") {
145
+ picture.type = "image/jpeg";
146
+ } else if (name === "picwgoal") {
147
+ picture.goalWidth = parameter;
148
+ } else if (name === "pichgoal") {
149
+ picture.goalHeight = parameter;
150
+ } else if (name === "picscalex" && parameter !== null && parameter > 0) {
151
+ picture.scaleX = parameter;
152
+ } else if (name === "picscaley" && parameter !== null && parameter > 0) {
153
+ picture.scaleY = parameter;
154
+ } else if (name === "bin" && parameter !== null && parameter > 0) {
155
+ for (let offset = 0; offset < parameter && index + offset < rtf.length; offset += 1) {
156
+ picture.binary.push(rtf.charCodeAt(index + offset) & 0xff);
157
+ }
158
+ index += parameter;
159
+ }
160
+ continue;
161
+ }
162
+ const picture = current().picture;
163
+ if (picture && !current().skip) {
164
+ // Hex data runs until the next control word or group.
165
+ let end = index;
166
+ while (end < rtf.length && rtf[end] !== "\\" && rtf[end] !== "{" && rtf[end] !== "}") {
167
+ end += 1;
168
+ }
169
+ let run = "";
170
+ for (let position = index; position < end; position += 1) {
171
+ if (isHexDigit(rtf.charCodeAt(position))) {
172
+ run += rtf[position];
173
+ }
174
+ }
175
+ picture.hex.push(run);
176
+ index = end;
177
+ continue;
178
+ }
179
+ index += 1;
180
+ }
181
+ return images;
182
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "lib": ["ES2022", "DOM"],
5
+ "rootDir": "src",
6
+ "outDir": "dist"
7
+ },
8
+ "include": ["src/**/*.ts"]
9
+ }