psd 4.0.0 → 4.2.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/README.md +146 -7
- package/dist/descriptor.js +6 -2
- package/dist/descriptor.js.map +1 -1
- package/dist/image.d.ts +28 -4
- package/dist/image.d.ts.map +1 -1
- package/dist/image.js +36 -22
- package/dist/image.js.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/layer-info.d.ts +53 -10
- package/dist/layer-info.d.ts.map +1 -1
- package/dist/layer-info.js +34 -8
- package/dist/layer-info.js.map +1 -1
- package/dist/layer-styles.d.ts +11 -1
- package/dist/layer-styles.d.ts.map +1 -1
- package/dist/layer-styles.js +5 -5
- package/dist/layer-styles.js.map +1 -1
- package/dist/layer.d.ts +32 -0
- package/dist/layer.d.ts.map +1 -1
- package/dist/layer.js +68 -6
- package/dist/layer.js.map +1 -1
- package/dist/linked-files.d.ts +32 -0
- package/dist/linked-files.d.ts.map +1 -0
- package/dist/linked-files.js +45 -0
- package/dist/linked-files.js.map +1 -0
- package/dist/nodes.d.ts +21 -9
- package/dist/nodes.d.ts.map +1 -1
- package/dist/nodes.js +16 -6
- package/dist/nodes.js.map +1 -1
- package/dist/path-record.d.ts +28 -0
- package/dist/path-record.d.ts.map +1 -1
- package/dist/path-record.js +54 -1
- package/dist/path-record.js.map +1 -1
- package/dist/patterns.d.ts +24 -0
- package/dist/patterns.d.ts.map +1 -0
- package/dist/patterns.js +108 -0
- package/dist/patterns.js.map +1 -0
- package/dist/png.d.ts +12 -4
- package/dist/png.d.ts.map +1 -1
- package/dist/png.js +68 -31
- package/dist/png.js.map +1 -1
- package/dist/psd.d.ts +13 -2
- package/dist/psd.d.ts.map +1 -1
- package/dist/psd.js +23 -1
- package/dist/psd.js.map +1 -1
- package/dist/resources.d.ts +7 -1
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +18 -0
- package/dist/resources.js.map +1 -1
- package/dist/shapes.d.ts +94 -0
- package/dist/shapes.d.ts.map +1 -0
- package/dist/shapes.js +76 -0
- package/dist/shapes.js.map +1 -0
- package/dist/type-tool.d.ts +60 -11
- package/dist/type-tool.d.ts.map +1 -1
- package/dist/type-tool.js +87 -17
- package/dist/type-tool.js.map +1 -1
- package/package.json +4 -2
- package/src/descriptor.ts +6 -2
- package/src/image.ts +56 -26
- package/src/index.ts +17 -5
- package/src/layer-info.ts +76 -8
- package/src/layer-styles.ts +8 -6
- package/src/layer.ts +79 -6
- package/src/linked-files.ts +66 -0
- package/src/nodes.ts +20 -6
- package/src/path-record.ts +63 -2
- package/src/patterns.ts +113 -0
- package/src/png.ts +76 -31
- package/src/psd.ts +25 -1
- package/src/resources.ts +21 -1
- package/src/shapes.ts +156 -0
- package/src/type-tool.ts +106 -17
package/src/path-record.ts
CHANGED
|
@@ -7,7 +7,17 @@ export interface PathPoint {
|
|
|
7
7
|
|
|
8
8
|
/** One 26-byte record of a vector path (vector masks, saved paths, the work path). */
|
|
9
9
|
export type PathRecord =
|
|
10
|
-
| {
|
|
10
|
+
| {
|
|
11
|
+
/** 0 starts a closed subpath, 3 an open one. */
|
|
12
|
+
recordType: 0 | 3;
|
|
13
|
+
numPoints: number;
|
|
14
|
+
/**
|
|
15
|
+
* How this subpath combines with the shape built from the ones before it. Undocumented by Adobe:
|
|
16
|
+
* 1 combine (union), 2 subtract, 3 intersect, 0 exclude (xor), and -1 for a subpath that belongs
|
|
17
|
+
* to the same component as the previous one, like the inner contour of a ring.
|
|
18
|
+
*/
|
|
19
|
+
operation: number;
|
|
20
|
+
}
|
|
11
21
|
| {
|
|
12
22
|
recordType: 1 | 2 | 4 | 5;
|
|
13
23
|
/** Closed subpath records are 1 and 2; open are 4 and 5. */
|
|
@@ -34,7 +44,7 @@ function readPathRecord(r: Reader): PathRecord {
|
|
|
34
44
|
switch (recordType) {
|
|
35
45
|
case 0:
|
|
36
46
|
case 3:
|
|
37
|
-
record = { recordType, numPoints: r.int16() };
|
|
47
|
+
record = { recordType, numPoints: r.int16(), operation: r.int16() };
|
|
38
48
|
break;
|
|
39
49
|
case 1:
|
|
40
50
|
case 2:
|
|
@@ -67,3 +77,54 @@ function readPathRecord(r: Reader): PathRecord {
|
|
|
67
77
|
r.seek(start + 26);
|
|
68
78
|
return record;
|
|
69
79
|
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Converts path records (`vectorMask.paths`, `workPath`, `savedPaths[].records`) to SVG path data, with one
|
|
83
|
+
* entry per shape component. Knot coordinates are fractions of the document size, so pass `psd.width` and
|
|
84
|
+
* `psd.height` to get document pixels.
|
|
85
|
+
*
|
|
86
|
+
* Fill each component with the even-odd rule. Photoshop then combines the components in order, starting
|
|
87
|
+
* from an empty canvas (or a full one if the first operation is subtract or intersect), by `operation`:
|
|
88
|
+
* 1 combine (union), 2 subtract, 3 intersect, 0 exclude (xor). The subpaths of one component, such as the
|
|
89
|
+
* two contours of a ring, share a `d`.
|
|
90
|
+
*
|
|
91
|
+
* Every knot becomes a cubic Bézier; closed subpaths end in `Z` and open ones don't. Other records,
|
|
92
|
+
* including the initial fill (8), are ignored. Throws if the knots don't match their subpath records.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* const [shape] = pathToSvg(node.info.vectorMask.paths, psd.width, psd.height);
|
|
96
|
+
* `<svg viewBox="0 0 ${psd.width} ${psd.height}"><path fill-rule="evenodd" d="${shape.d}"/></svg>`;
|
|
97
|
+
*/
|
|
98
|
+
export function pathToSvg(records: readonly PathRecord[], width: number, height: number): { operation: number; d: string }[] {
|
|
99
|
+
const num = (n: number) => String(Math.round(n * 1000) / 1000 + 0); // + 0 turns -0 into 0
|
|
100
|
+
const xy = (p: PathPoint) => `${num(p.horiz * width)} ${num(p.vert * height)}`;
|
|
101
|
+
type Knot = Extract<PathRecord, { anchor: PathPoint }>;
|
|
102
|
+
const subpaths: { closed: boolean; operation: number; numPoints: number; knots: Knot[] }[] = [];
|
|
103
|
+
|
|
104
|
+
records.forEach((record, i) => {
|
|
105
|
+
if (record.recordType === 0 || record.recordType === 3) {
|
|
106
|
+
subpaths.push({ closed: record.recordType === 0, operation: record.operation, numPoints: record.numPoints, knots: [] });
|
|
107
|
+
} else if ('anchor' in record) {
|
|
108
|
+
const subpath = subpaths.at(-1);
|
|
109
|
+
if (!subpath || subpath.knots.length === subpath.numPoints || subpath.closed !== record.closed) {
|
|
110
|
+
throw new Error(`Path record ${i} is a knot outside of a ${record.closed ? 'closed' : 'open'} subpath`);
|
|
111
|
+
}
|
|
112
|
+
subpath.knots.push(record);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
const components: { operation: number; d: string }[] = [];
|
|
117
|
+
for (const { closed, operation, numPoints, knots } of subpaths) {
|
|
118
|
+
if (knots.length !== numPoints) throw new Error(`Subpath has ${knots.length} of its ${numPoints} knots`);
|
|
119
|
+
let d = '';
|
|
120
|
+
if (knots.length) {
|
|
121
|
+
const segments = knots.slice(1).map((k, i) => `C${xy(knots[i]!.leaving)} ${xy(k.preceding)} ${xy(k.anchor)}`);
|
|
122
|
+
if (closed) segments.push(`C${xy(knots.at(-1)!.leaving)} ${xy(knots[0]!.preceding)} ${xy(knots[0]!.anchor)}Z`);
|
|
123
|
+
d = `M${xy(knots[0]!.anchor)}${segments.join('')}`;
|
|
124
|
+
}
|
|
125
|
+
if (operation !== -1) components.push({ operation, d });
|
|
126
|
+
else if (components.length) components.at(-1)!.d += d;
|
|
127
|
+
else throw new Error('The first subpath continues a shape component that does not exist');
|
|
128
|
+
}
|
|
129
|
+
return components;
|
|
130
|
+
}
|
package/src/patterns.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { decodePlanes, type Plane, type RGBAImage } from './image.ts';
|
|
2
|
+
import { encodePng } from './png.ts';
|
|
3
|
+
import { MODES, type Header } from './psd.ts';
|
|
4
|
+
import type { Reader } from './reader.ts';
|
|
5
|
+
|
|
6
|
+
interface PatternPlane extends Plane {
|
|
7
|
+
depth: number;
|
|
8
|
+
width: number;
|
|
9
|
+
height: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A pattern from the document's `Patt`, `Pat2` or `Pat3` blocks. Pattern fills and overlays refer
|
|
14
|
+
* to it by `id`. The pixels are decoded on demand.
|
|
15
|
+
*/
|
|
16
|
+
export class Pattern {
|
|
17
|
+
/** The unique ID that pattern fills (`info.patternFill.Ptrn.Idnt`) and layer styles (`pattern.id`) refer to. */
|
|
18
|
+
readonly id: string;
|
|
19
|
+
/** The name. Photoshop's presets have localizable names like `$$$/Presets/Patterns/Water=Water`. */
|
|
20
|
+
readonly name: string;
|
|
21
|
+
readonly width: number;
|
|
22
|
+
readonly height: number;
|
|
23
|
+
/** Color mode ID, as in `psd.header.mode`. */
|
|
24
|
+
readonly mode: number;
|
|
25
|
+
readonly #reader: Reader;
|
|
26
|
+
readonly #colorTable: Uint8Array = new Uint8Array(0);
|
|
27
|
+
readonly #planes: PatternPlane[] = [];
|
|
28
|
+
|
|
29
|
+
constructor(r: Reader) {
|
|
30
|
+
this.#reader = r;
|
|
31
|
+
const version = r.uint32();
|
|
32
|
+
if (version !== 1) throw new Error(`Unsupported pattern version ${version}`);
|
|
33
|
+
this.mode = r.uint32();
|
|
34
|
+
r.skip(4); // height and width (2 bytes each), also in the rectangle below
|
|
35
|
+
this.name = r.unicode();
|
|
36
|
+
this.id = r.pascal();
|
|
37
|
+
|
|
38
|
+
// An indexed pattern's color table is 256 RGB triplets. The 4 bytes after it are undocumented
|
|
39
|
+
// and skipped as in psd-tools. The decoder wants the reds, then the greens, then the blues.
|
|
40
|
+
if (this.mode === 2) {
|
|
41
|
+
const table = r.bytesView(768);
|
|
42
|
+
this.#colorTable = new Uint8Array(768);
|
|
43
|
+
for (let i = 0; i < 768; i++) this.#colorTable[(i % 3) * 256 + Math.floor(i / 3)] = table[i]!;
|
|
44
|
+
r.skip(4);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The pixels are a "virtual memory array list": a rectangle and a slot for each channel, and
|
|
48
|
+
// two more slots for a user mask and the transparency.
|
|
49
|
+
const listVersion = r.uint32();
|
|
50
|
+
if (listVersion !== 3) throw new Error(`Unsupported pattern data version ${listVersion}`);
|
|
51
|
+
r.skip(4); // length
|
|
52
|
+
const [top, left, bottom, right] = [r.uint32(), r.uint32(), r.uint32(), r.uint32()];
|
|
53
|
+
this.width = right - left;
|
|
54
|
+
this.height = bottom - top;
|
|
55
|
+
const colorSlots = r.uint32();
|
|
56
|
+
for (let slot = 0; slot < colorSlots + 2; slot++) {
|
|
57
|
+
if (r.uint32() === 0) continue; // not written
|
|
58
|
+
const length = r.uint32();
|
|
59
|
+
if (length === 0) continue;
|
|
60
|
+
const end = r.pos + length;
|
|
61
|
+
const depth = r.uint32();
|
|
62
|
+
const [planeTop, planeLeft, planeBottom, planeRight] = [r.uint32(), r.uint32(), r.uint32(), r.uint32()];
|
|
63
|
+
r.skip(2); // pixel depth again
|
|
64
|
+
const compression = r.uint8();
|
|
65
|
+
// Written color slots are the color channels in order; the last slot is the transparency.
|
|
66
|
+
const id = slot < colorSlots ? this.#planes.length : slot === colorSlots + 1 ? -1 : undefined;
|
|
67
|
+
const [width, height] = [planeRight - planeLeft, planeBottom - planeTop];
|
|
68
|
+
if (id !== undefined) this.#planes.push({ id, compression, offset: r.pos, end, depth, width, height });
|
|
69
|
+
r.seek(end);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Decodes the pixels. Each call decodes again. */
|
|
74
|
+
async decode(): Promise<RGBAImage> {
|
|
75
|
+
const planes = this.#planes;
|
|
76
|
+
const depth = planes[0]?.depth;
|
|
77
|
+
if (depth === undefined) throw new Error(`Pattern '${this.name}' has no pixel data`);
|
|
78
|
+
for (const p of planes) {
|
|
79
|
+
if (p.depth !== depth || p.width !== this.width || p.height !== this.height) {
|
|
80
|
+
throw new Error(`Pattern '${this.name}' has channels of different sizes or depths`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const header: Header = {
|
|
84
|
+
version: 1,
|
|
85
|
+
isBig: false, // RLE row lengths are 2 bytes even in PSB files
|
|
86
|
+
channels: planes.filter((p) => p.id >= 0).length,
|
|
87
|
+
width: this.width,
|
|
88
|
+
height: this.height,
|
|
89
|
+
depth,
|
|
90
|
+
mode: this.mode,
|
|
91
|
+
modeName: MODES[this.mode] ?? 'Unknown',
|
|
92
|
+
colorModeData: this.#colorTable,
|
|
93
|
+
};
|
|
94
|
+
return decodePlanes(this.#reader, header, planes);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async toPng(): Promise<Uint8Array> {
|
|
98
|
+
return encodePng(await this.decode());
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Reads the patterns in a `Patt`, `Pat2` or `Pat3` block. */
|
|
103
|
+
export function readPatterns(r: Reader, end: number): Pattern[] {
|
|
104
|
+
const patterns: Pattern[] = [];
|
|
105
|
+
// Each pattern is a length-prefixed record padded to 4 bytes.
|
|
106
|
+
while (r.pos + 4 <= end) {
|
|
107
|
+
const length = r.uint32();
|
|
108
|
+
if (r.pos + length > end) throw new Error(`Pattern of ${length} bytes overruns its block`);
|
|
109
|
+
patterns.push(new Pattern(r.at(r.pos)));
|
|
110
|
+
r.skip((length + 3) & ~3);
|
|
111
|
+
}
|
|
112
|
+
return patterns;
|
|
113
|
+
}
|
package/src/png.ts
CHANGED
|
@@ -5,38 +5,78 @@ export interface Pixels {
|
|
|
5
5
|
data: Uint8Array | Uint8ClampedArray;
|
|
6
6
|
}
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
/** Writes the chunks to a (de)compression stream as they're produced and returns its output chunks. */
|
|
9
|
+
async function transform(input: Iterable<Uint8Array>, stream: CompressionStream | DecompressionStream): Promise<Uint8Array[]> {
|
|
10
|
+
const writer = stream.writable.getWriter();
|
|
11
|
+
const reader = stream.readable.getReader();
|
|
12
|
+
const output: Uint8Array[] = [];
|
|
13
|
+
const write = async () => {
|
|
14
|
+
for (const bytes of input) await writer.write(bytes as Uint8Array<ArrayBuffer>);
|
|
15
|
+
await writer.close();
|
|
16
|
+
};
|
|
17
|
+
const read = async () => {
|
|
18
|
+
for (let r = await reader.read(); !r.done; r = await reader.read()) output.push(r.value);
|
|
19
|
+
};
|
|
20
|
+
await Promise.all([write(), read()]);
|
|
21
|
+
return output;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function concat(parts: Uint8Array[]): Uint8Array {
|
|
25
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
26
|
+
let offset = 0;
|
|
27
|
+
for (const p of parts) {
|
|
28
|
+
out.set(p, offset);
|
|
29
|
+
offset += p.length;
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
10
33
|
|
|
11
|
-
export const inflate = (bytes: Uint8Array) => transform(bytes, new DecompressionStream('deflate'));
|
|
12
|
-
export const deflate = (bytes: Uint8Array) => transform(bytes, new CompressionStream('deflate'));
|
|
34
|
+
export const inflate = async (bytes: Uint8Array) => concat(await transform([bytes], new DecompressionStream('deflate')));
|
|
13
35
|
|
|
14
36
|
const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
|
|
15
37
|
for (let k = 0; k < 8; k++) n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1;
|
|
16
38
|
return n >>> 0;
|
|
17
39
|
});
|
|
18
40
|
|
|
19
|
-
function crc32(
|
|
41
|
+
function crc32(parts: Uint8Array[]): number {
|
|
20
42
|
let crc = 0xffffffff;
|
|
21
|
-
for (const b of bytes) crc = CRC_TABLE[(crc ^ b) & 0xff]! ^ (crc >>> 8);
|
|
43
|
+
for (const bytes of parts) for (const b of bytes) crc = CRC_TABLE[(crc ^ b) & 0xff]! ^ (crc >>> 8);
|
|
22
44
|
return (crc ^ 0xffffffff) >>> 0;
|
|
23
45
|
}
|
|
24
46
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
for (let i = 0; i < 4; i++)
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return
|
|
47
|
+
/** A PNG chunk as a list of parts, so large data isn't copied until the file is assembled. */
|
|
48
|
+
function chunk(type: string, data: Uint8Array[]): Uint8Array[] {
|
|
49
|
+
const head = new Uint8Array(8);
|
|
50
|
+
new DataView(head.buffer).setUint32(0, data.reduce((n, d) => n + d.length, 0));
|
|
51
|
+
for (let i = 0; i < 4; i++) head[4 + i] = type.charCodeAt(i);
|
|
52
|
+
const crc = new Uint8Array(4);
|
|
53
|
+
new DataView(crc.buffer).setUint32(0, crc32([head.subarray(4), ...data]));
|
|
54
|
+
return [head, ...data, crc];
|
|
33
55
|
}
|
|
34
56
|
|
|
35
|
-
|
|
36
|
-
|
|
57
|
+
export interface PngOptions {
|
|
58
|
+
/**
|
|
59
|
+
* An ICC profile to embed, such as `psd.resources.iccProfile`. Its color space must match the
|
|
60
|
+
* pixels: RGB for RGBA pixels and grayscale for grayscale pixels.
|
|
61
|
+
*/
|
|
62
|
+
iccProfile?: Uint8Array;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The color space signature of an ICC profile, such as `'RGB '`, `'GRAY'` or `'CMYK'`. */
|
|
66
|
+
export const iccColorSpace = (profile: Uint8Array) => String.fromCharCode(...profile.subarray(16, 20));
|
|
67
|
+
|
|
68
|
+
/** The iCCP chunk's profile name, its NUL terminator and compression method 0 (zlib). */
|
|
69
|
+
const ICCP_NAME = new TextEncoder().encode('ICC profile\0\0');
|
|
70
|
+
|
|
71
|
+
/** Encodes 8-bit grayscale or RGBA pixels as a PNG file, optionally with an ICC profile. */
|
|
72
|
+
export async function encodePng({ width, height, data }: Pixels, { iccProfile }: PngOptions = {}): Promise<Uint8Array> {
|
|
37
73
|
if (width === 0 || height === 0) throw new Error('Cannot encode an empty image as PNG');
|
|
38
74
|
const channels = data.length / (width * height);
|
|
39
75
|
if (channels !== 1 && channels !== 4) throw new Error(`Expected 1 or 4 bytes per pixel, got ${channels}`);
|
|
76
|
+
const space = iccProfile && iccColorSpace(iccProfile);
|
|
77
|
+
if (space !== undefined && space !== (channels === 4 ? 'RGB ' : 'GRAY')) {
|
|
78
|
+
throw new Error(`Cannot embed a '${space}' ICC profile in a ${channels === 4 ? 'RGBA' : 'grayscale'} PNG`);
|
|
79
|
+
}
|
|
40
80
|
|
|
41
81
|
const header = new Uint8Array(13);
|
|
42
82
|
const view = new DataView(header.buffer);
|
|
@@ -45,22 +85,27 @@ export async function encodePng({ width, height, data }: Pixels): Promise<Uint8A
|
|
|
45
85
|
header[8] = 8; // bit depth
|
|
46
86
|
header[9] = channels === 4 ? 6 : 0; // RGBA or grayscale
|
|
47
87
|
|
|
48
|
-
// Each row is prefixed with filter type 0 (none).
|
|
88
|
+
// Each row is prefixed with filter type 0 (none). Rows are compressed about 1MB at a time
|
|
89
|
+
// rather than copied into one buffer, which would double the image's memory.
|
|
49
90
|
const rowLength = width * channels;
|
|
50
|
-
const
|
|
51
|
-
|
|
91
|
+
const blockRows = Math.max(1, Math.floor(2 ** 20 / (rowLength + 1)));
|
|
92
|
+
function* rows() {
|
|
93
|
+
for (let start = 0; start < height; start += blockRows) {
|
|
94
|
+
const count = Math.min(blockRows, height - start);
|
|
95
|
+
const block = new Uint8Array((rowLength + 1) * count);
|
|
96
|
+
for (let y = 0; y < count; y++) {
|
|
97
|
+
const row = (start + y) * rowLength;
|
|
98
|
+
block.set(data.subarray(row, row + rowLength), y * (rowLength + 1) + 1);
|
|
99
|
+
}
|
|
100
|
+
yield block;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
52
103
|
|
|
53
|
-
|
|
104
|
+
return concat([
|
|
54
105
|
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
55
|
-
chunk('IHDR', header),
|
|
56
|
-
chunk('
|
|
57
|
-
chunk('
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
let offset = 0;
|
|
61
|
-
for (const p of parts) {
|
|
62
|
-
png.set(p, offset);
|
|
63
|
-
offset += p.length;
|
|
64
|
-
}
|
|
65
|
-
return png;
|
|
106
|
+
...chunk('IHDR', [header]),
|
|
107
|
+
...(iccProfile ? chunk('iCCP', [ICCP_NAME, ...(await transform([iccProfile], new CompressionStream('deflate')))]) : []),
|
|
108
|
+
...chunk('IDAT', await transform(rows(), new CompressionStream('deflate'))),
|
|
109
|
+
...chunk('IEND', []),
|
|
110
|
+
]);
|
|
66
111
|
}
|
package/src/psd.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { CompositeImage } from './image.ts';
|
|
2
2
|
import { readLayerSection, type GlobalMask, type Layer, type LayerSection } from './layer.ts';
|
|
3
|
+
import { readLinkedFiles, type LinkedFile } from './linked-files.ts';
|
|
3
4
|
import { RootNode } from './nodes.ts';
|
|
5
|
+
import { readPatterns, type Pattern } from './patterns.ts';
|
|
4
6
|
import { Reader } from './reader.ts';
|
|
5
7
|
import { Resources } from './resources.ts';
|
|
6
8
|
|
|
7
|
-
const MODES = [
|
|
9
|
+
export const MODES = [
|
|
8
10
|
'Bitmap',
|
|
9
11
|
'GrayScale',
|
|
10
12
|
'IndexedColor',
|
|
@@ -75,6 +77,8 @@ export class PSD {
|
|
|
75
77
|
#layerSection: LayerSection | undefined;
|
|
76
78
|
#image: CompositeImage | undefined;
|
|
77
79
|
#tree: RootNode | undefined;
|
|
80
|
+
#patterns: Pattern[] | undefined;
|
|
81
|
+
#linkedFiles: LinkedFile[] | undefined;
|
|
78
82
|
|
|
79
83
|
constructor(data: ArrayBuffer | ArrayBufferView) {
|
|
80
84
|
const bytes = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
|
|
@@ -121,6 +125,26 @@ export class PSD {
|
|
|
121
125
|
return this.#layers.globalMask;
|
|
122
126
|
}
|
|
123
127
|
|
|
128
|
+
/**
|
|
129
|
+
* The patterns used by pattern fills, overlays and strokes, which refer to them by `id`.
|
|
130
|
+
* Pixels are decoded on demand with `pattern.decode()`.
|
|
131
|
+
*/
|
|
132
|
+
get patterns(): Pattern[] {
|
|
133
|
+
return (this.#patterns ??= this.#layers.infoBlocks
|
|
134
|
+
.filter((b) => ['Patt', 'Pat2', 'Pat3'].includes(b.key))
|
|
135
|
+
.flatMap((b) => readPatterns(this.#reader.at(b.offset), b.offset + b.length)));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Files placed as smart objects, embedded or linked. A smart object layer's file is
|
|
140
|
+
* `node.linkedFile`. File contents aren't copied out of the document.
|
|
141
|
+
*/
|
|
142
|
+
get linkedFiles(): LinkedFile[] {
|
|
143
|
+
return (this.#linkedFiles ??= this.#layers.infoBlocks
|
|
144
|
+
.filter((b) => ['lnk2', 'lnk3', 'lnkD', 'lnkE'].includes(b.key))
|
|
145
|
+
.flatMap((b) => readLinkedFiles(this.#reader.at(b.offset), b.offset + b.length)));
|
|
146
|
+
}
|
|
147
|
+
|
|
124
148
|
/** The flattened composite image. */
|
|
125
149
|
get image(): CompositeImage {
|
|
126
150
|
return (this.#image ??= new CompositeImage(this.#reader.at(this.#imageOffset), this.header, () => this.resources));
|
package/src/resources.ts
CHANGED
|
@@ -24,7 +24,7 @@ export interface Guide {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
export interface ResolutionInfo {
|
|
27
|
-
/** Horizontal resolution in pixels per `hResUnitName
|
|
27
|
+
/** Horizontal resolution in pixels per inch. `hResUnitName` is only the unit Photoshop displays it in. */
|
|
28
28
|
hRes: number;
|
|
29
29
|
hResUnit: number;
|
|
30
30
|
hResUnitName: string;
|
|
@@ -203,6 +203,26 @@ export class Resources {
|
|
|
203
203
|
return this.#parse(1047, (r) => r.uint16());
|
|
204
204
|
}
|
|
205
205
|
|
|
206
|
+
/** Resource 1039: the document's ICC color profile. */
|
|
207
|
+
get iccProfile(): Uint8Array | undefined {
|
|
208
|
+
return this.#parse(1039, (r, block) => {
|
|
209
|
+
// The block is padded to an even length; the profile header has the exact size.
|
|
210
|
+
const size = r.view.getUint32(r.pos);
|
|
211
|
+
if (size < 128 || size > block.size) throw new Error(`Invalid ICC profile size ${size} in a ${block.size} byte resource`);
|
|
212
|
+
return r.bytesView(size);
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Resource 1037: the global light angle in degrees, used by layer styles with `useGlobalLight`. */
|
|
217
|
+
get globalAngle(): number | undefined {
|
|
218
|
+
return this.#parse(1037, (r) => r.int32());
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Resource 1049: the global light altitude in degrees, used by bevels with `useGlobalLight`. */
|
|
222
|
+
get globalAltitude(): number | undefined {
|
|
223
|
+
return this.#parse(1049, (r) => r.int32());
|
|
224
|
+
}
|
|
225
|
+
|
|
206
226
|
/** Resource 1026: the group ID of each layer, ordered top to bottom like `psd.layers`. */
|
|
207
227
|
get layerGroups(): number[] | undefined {
|
|
208
228
|
return this.#parse(1026, (r, block) => Array.from({ length: block.size / 2 }, () => r.uint16()).reverse());
|
package/src/shapes.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import type { Descriptor, UnitValue } from './descriptor.ts';
|
|
2
|
+
import type { BlendMode } from './layer.ts';
|
|
3
|
+
import { blendMode, descriptorColor, enumValue, gradient, pattern, percent, type Gradient, type RGB } from './layer-styles.ts';
|
|
4
|
+
import type { Bounds } from './resources.ts';
|
|
5
|
+
|
|
6
|
+
/** A shape's fill or stroke content. One of these is set, depending on its type. */
|
|
7
|
+
export interface ShapeContent {
|
|
8
|
+
/** Undefined for colors that can't be converted, such as book colors. */
|
|
9
|
+
color: RGB | undefined;
|
|
10
|
+
gradient: Gradient | undefined;
|
|
11
|
+
pattern: { name: string; id: string } | undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The live shape properties Photoshop keeps for each shape tool shape in a layer. */
|
|
15
|
+
export interface VectorShape {
|
|
16
|
+
/** Undefined if the shape was edited into a plain path, or for shape types this library doesn't know. */
|
|
17
|
+
type: 'rectangle' | 'roundedRectangle' | 'line' | 'ellipse' | undefined;
|
|
18
|
+
/** The shape was edited with the path tools, so it only has `index` and `data`. */
|
|
19
|
+
invalidated: boolean;
|
|
20
|
+
/** The shape's path component in the vector mask (`info.vectorMask`). */
|
|
21
|
+
index: number;
|
|
22
|
+
/**
|
|
23
|
+
* The shape's bounds in pixels, as shown in Photoshop's Properties panel. The layer's bounds are
|
|
24
|
+
* larger: they're whole pixels, and include antialiasing and the stroke.
|
|
25
|
+
*/
|
|
26
|
+
bounds: Bounds | undefined;
|
|
27
|
+
/** Rounded rectangle corner radii, in pixels. */
|
|
28
|
+
radii: { topLeft: number; topRight: number; bottomRight: number; bottomLeft: number } | undefined;
|
|
29
|
+
/** Line endpoints in pixels, and the line's weight. */
|
|
30
|
+
line: { start: { x: number; y: number }; end: { x: number; y: number }; weight: number } | undefined;
|
|
31
|
+
/** The raw descriptor, for anything not covered above (rotated corners, arrowheads...). */
|
|
32
|
+
data: Descriptor;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A shape layer's stroke settings, and whether its fill and stroke are shown. */
|
|
36
|
+
export interface VectorStroke extends ShapeContent {
|
|
37
|
+
/** Whether the stroke is shown. */
|
|
38
|
+
enabled: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Whether the fill is shown. The fill's content is in `vectorStrokeContent`, or `solidColor`,
|
|
41
|
+
* `gradientFill` or `patternFill` for older shapes.
|
|
42
|
+
*/
|
|
43
|
+
fillEnabled: boolean;
|
|
44
|
+
/** In pixels. */
|
|
45
|
+
width: number;
|
|
46
|
+
alignment: 'inside' | 'center' | 'outside' | undefined;
|
|
47
|
+
cap: 'butt' | 'round' | 'square' | undefined;
|
|
48
|
+
join: 'miter' | 'round' | 'bevel' | undefined;
|
|
49
|
+
miterLimit: number;
|
|
50
|
+
/** Alternating dash and gap lengths, as multiples of the width. Empty for a solid line. */
|
|
51
|
+
dashes: number[];
|
|
52
|
+
/** In pixels. */
|
|
53
|
+
dashOffset: number;
|
|
54
|
+
/** 0 to 1. */
|
|
55
|
+
opacity: number;
|
|
56
|
+
blendMode: BlendMode | string | undefined;
|
|
57
|
+
/** The raw descriptor, for anything not covered above. */
|
|
58
|
+
data: Descriptor;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The live shape properties Photoshop keeps for a shape layer (`vogk`). */
|
|
62
|
+
export interface VectorOrigination {
|
|
63
|
+
/** One entry per shape tool shape in the layer. */
|
|
64
|
+
shapes: VectorShape[];
|
|
65
|
+
/** The raw descriptor, for anything not covered above. */
|
|
66
|
+
data: Descriptor;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A newer shape layer's fill (`vscg`). */
|
|
70
|
+
export interface VectorFill extends ShapeContent {
|
|
71
|
+
/** The raw descriptor, for anything not covered above. */
|
|
72
|
+
data: Descriptor;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const SHAPE_TYPES = { 1: 'rectangle', 2: 'roundedRectangle', 4: 'line', 5: 'ellipse' } as const;
|
|
76
|
+
const ALIGNMENTS = { strokeStyleAlignInside: 'inside', strokeStyleAlignCenter: 'center', strokeStyleAlignOutside: 'outside' } as const;
|
|
77
|
+
const CAPS = { strokeStyleButtCap: 'butt', strokeStyleRoundCap: 'round', strokeStyleSquareCap: 'square' } as const;
|
|
78
|
+
const JOINS = { strokeStyleMiterJoin: 'miter', strokeStyleRoundJoin: 'round', strokeStyleBevelJoin: 'bevel' } as const;
|
|
79
|
+
|
|
80
|
+
const lookup = <T extends Record<string, string>>(table: T, v: unknown): T[keyof T] | undefined =>
|
|
81
|
+
table[enumValue(v) as keyof T];
|
|
82
|
+
|
|
83
|
+
/** Converts a unit value to pixels at the given resolution (pixels per inch). */
|
|
84
|
+
function pixels(v: UnitValue, resolution: number): number {
|
|
85
|
+
switch (v.id) {
|
|
86
|
+
case '#Pxl':
|
|
87
|
+
return v.value;
|
|
88
|
+
case '#Pnt':
|
|
89
|
+
return (v.value * resolution) / 72;
|
|
90
|
+
case '#Mlm':
|
|
91
|
+
return (v.value * resolution) / 25.4;
|
|
92
|
+
default:
|
|
93
|
+
throw new Error(`Unsupported shape unit '${v.id}'`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export const shapeContent = (d: Descriptor | undefined): ShapeContent => ({
|
|
98
|
+
color: descriptorColor(d?.['Clr ']),
|
|
99
|
+
gradient: gradient(d?.Grad),
|
|
100
|
+
pattern: pattern(d?.Ptrn),
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
function vectorShape(d: Descriptor): VectorShape {
|
|
104
|
+
const res: number = d.keyOriginResolution;
|
|
105
|
+
const px = (v: UnitValue) => pixels(v, res);
|
|
106
|
+
const box = d.keyOriginShapeBBox;
|
|
107
|
+
const radii = d.keyOriginRRectRadii;
|
|
108
|
+
const point = (p: Descriptor) => ({ x: p.Hrzn as number, y: p.Vrtc as number });
|
|
109
|
+
return {
|
|
110
|
+
type: SHAPE_TYPES[d.keyOriginType as keyof typeof SHAPE_TYPES],
|
|
111
|
+
invalidated: d.keyShapeInvalidated ?? false,
|
|
112
|
+
index: d.keyOriginIndex,
|
|
113
|
+
bounds: box && { top: px(box['Top ']), left: px(box.Left), bottom: px(box.Btom), right: px(box.Rght) },
|
|
114
|
+
radii: radii && {
|
|
115
|
+
topLeft: px(radii.topLeft),
|
|
116
|
+
topRight: px(radii.topRight),
|
|
117
|
+
bottomRight: px(radii.bottomRight),
|
|
118
|
+
bottomLeft: px(radii.bottomLeft),
|
|
119
|
+
},
|
|
120
|
+
line: d.keyOriginLineStart && {
|
|
121
|
+
start: point(d.keyOriginLineStart),
|
|
122
|
+
end: point(d.keyOriginLineEnd),
|
|
123
|
+
weight: d.keyOriginLineWeight,
|
|
124
|
+
},
|
|
125
|
+
data: d,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Normalizes the vector origination (`vogk`) descriptor. */
|
|
130
|
+
export const readVectorOrigination = (d: Descriptor): VectorOrigination => ({
|
|
131
|
+
shapes: (d.keyDescriptorList ?? []).map(vectorShape),
|
|
132
|
+
data: d,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
/** Normalizes the vector fill (`vscg`) descriptor. */
|
|
136
|
+
export const readVectorFill = (d: Descriptor): VectorFill => ({ ...shapeContent(d), data: d });
|
|
137
|
+
|
|
138
|
+
/** Normalizes the vector stroke (`vstk`) descriptor. */
|
|
139
|
+
export function readVectorStroke(d: Descriptor): VectorStroke {
|
|
140
|
+
const res: number = d.strokeStyleResolution;
|
|
141
|
+
return {
|
|
142
|
+
...shapeContent(d.strokeStyleContent),
|
|
143
|
+
enabled: d.strokeEnabled,
|
|
144
|
+
fillEnabled: d.fillEnabled,
|
|
145
|
+
width: pixels(d.strokeStyleLineWidth, res),
|
|
146
|
+
alignment: lookup(ALIGNMENTS, d.strokeStyleLineAlignment),
|
|
147
|
+
cap: lookup(CAPS, d.strokeStyleLineCapType),
|
|
148
|
+
join: lookup(JOINS, d.strokeStyleLineJoinType),
|
|
149
|
+
miterLimit: d.strokeStyleMiterLimit,
|
|
150
|
+
dashes: d.strokeStyleLineDashSet.map((v: UnitValue) => v.value),
|
|
151
|
+
dashOffset: pixels(d.strokeStyleLineDashOffset, res),
|
|
152
|
+
opacity: percent(d.strokeStyleOpacity),
|
|
153
|
+
blendMode: blendMode(d.strokeStyleBlendMode),
|
|
154
|
+
data: d,
|
|
155
|
+
};
|
|
156
|
+
}
|