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/image.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ChannelInfo, Layer } from './layer.ts';
|
|
2
|
-
import { encodePng, inflate } from './png.ts';
|
|
2
|
+
import { encodePng, iccColorSpace, inflate } from './png.ts';
|
|
3
3
|
import type { Header } from './psd.ts';
|
|
4
4
|
import type { Reader } from './reader.ts';
|
|
5
5
|
import type { Resources } from './resources.ts';
|
|
@@ -30,7 +30,7 @@ interface ColorModel {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
/** The color model for a document. Throws for formats this library can't decode. Resources are only read for indexed images. */
|
|
33
|
-
function colorModel(header: Header, resources: () => Resources): ColorModel {
|
|
33
|
+
function colorModel(header: Header, resources: () => Pick<Resources, 'indexedColorCount' | 'transparencyIndex'>): ColorModel {
|
|
34
34
|
const { mode, depth, channels, modeName } = header;
|
|
35
35
|
if ((mode === 0) !== (depth === 1)) throw new Error(`Decoding ${depth}-bit ${modeName} images is not supported`);
|
|
36
36
|
switch (mode) {
|
|
@@ -181,13 +181,12 @@ function to8Bit(data: Uint8Array, depth: number, width: number, height: number):
|
|
|
181
181
|
}
|
|
182
182
|
|
|
183
183
|
/**
|
|
184
|
-
* Decodes `count` planes stored back to back
|
|
184
|
+
* Decodes `count` planes stored back to back with a single compression type, as 8-bit samples.
|
|
185
185
|
* The composite image is stored this way, and so is each layer channel (with a count of 1).
|
|
186
186
|
*/
|
|
187
|
-
async function readPlanes(r: Reader, end: number, count: number, width: number, height: number, header: Header): Promise<Uint8Array[]> {
|
|
187
|
+
async function readPlanes(r: Reader, compression: number, end: number, count: number, width: number, height: number, header: Header): Promise<Uint8Array[]> {
|
|
188
188
|
const { depth } = header;
|
|
189
189
|
if (depth !== 1 && depth !== 8 && depth !== 16) throw new Error(`Decoding ${depth}-bit images is not supported`);
|
|
190
|
-
const compression = r.uint16();
|
|
191
190
|
if (width === 0 || height === 0) return Array.from({ length: count }, () => new Uint8Array());
|
|
192
191
|
|
|
193
192
|
const stride = rowBytes(width, depth);
|
|
@@ -217,8 +216,29 @@ async function readPlanes(r: Reader, end: number, count: number, width: number,
|
|
|
217
216
|
}
|
|
218
217
|
|
|
219
218
|
/** Decodes a single layer channel. */
|
|
220
|
-
|
|
221
|
-
|
|
219
|
+
async function readLayerChannel(reader: Reader, channel: ChannelInfo, width: number, height: number, header: Header) {
|
|
220
|
+
const r = reader.at(channel.offset);
|
|
221
|
+
return (await readPlanes(r, r.uint16(), channel.offset + channel.length, 1, width, height, header))[0]!;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** A separately compressed plane, such as a pattern channel. */
|
|
225
|
+
export interface Plane {
|
|
226
|
+
/** 0, 1, 2... for colors, -1 for transparency. */
|
|
227
|
+
id: number;
|
|
228
|
+
compression: number;
|
|
229
|
+
/** Where the compressed data starts and ends. */
|
|
230
|
+
offset: number;
|
|
231
|
+
end: number;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Decodes planes to RGBA. `header` describes the planes, not the document; indexed colors come from its `colorModeData` with no transparent index. */
|
|
235
|
+
export async function decodePlanes(reader: Reader, header: Header, planes: Plane[]): Promise<RGBAImage> {
|
|
236
|
+
const { width, height } = header;
|
|
237
|
+
const model = colorModel(header, () => ({ indexedColorCount: undefined, transparencyIndex: undefined }));
|
|
238
|
+
const decoded = new Map<number, Uint8Array>();
|
|
239
|
+
for (const p of planes) decoded.set(p.id, (await readPlanes(reader.at(p.offset), p.compression, p.end, 1, width, height, header))[0]!);
|
|
240
|
+
return { width, height, data: toRgba(model, decoded, width * height) };
|
|
241
|
+
}
|
|
222
242
|
|
|
223
243
|
/** Converts a cyan, magenta or yellow ink amount and the black amount to the matching RGB component. */
|
|
224
244
|
const inkToRgb = (ink: number, k: number) => Math.min(Math.max((65535 - (ink * (255 - k) + (k << 8))) >> 8, 0), 255);
|
|
@@ -241,12 +261,25 @@ export function labToRgb(l: number, a: number, b: number): [number, number, numb
|
|
|
241
261
|
];
|
|
242
262
|
}
|
|
243
263
|
|
|
264
|
+
export interface ToPngOptions {
|
|
265
|
+
/**
|
|
266
|
+
* Embed the document's ICC profile when it's an RGB profile. Defaults to `true`. Turn it off for
|
|
267
|
+
* smaller files when the colors are sRGB anyway, or when you manage color yourself.
|
|
268
|
+
*/
|
|
269
|
+
embedProfile?: boolean;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The document's ICC profile if it should be embedded in an RGBA PNG; CMYK, Lab and grayscale profiles can't be. */
|
|
273
|
+
function rgbProfile(resources: Resources, { embedProfile = true }: ToPngOptions): Uint8Array | undefined {
|
|
274
|
+
const profile = embedProfile ? resources.iccProfile : undefined;
|
|
275
|
+
return profile && iccColorSpace(profile) === 'RGB ' ? profile : undefined;
|
|
276
|
+
}
|
|
277
|
+
|
|
244
278
|
/** The flattened composite image stored at the end of the file. */
|
|
245
279
|
export class CompositeImage {
|
|
246
280
|
readonly #reader: Reader;
|
|
247
281
|
readonly #header: Header;
|
|
248
282
|
readonly #resources: () => Resources;
|
|
249
|
-
#decoded: Promise<RGBAImage> | undefined;
|
|
250
283
|
|
|
251
284
|
constructor(reader: Reader, header: Header, resources: () => Resources) {
|
|
252
285
|
this.#reader = reader;
|
|
@@ -264,18 +297,15 @@ export class CompositeImage {
|
|
|
264
297
|
|
|
265
298
|
/**
|
|
266
299
|
* Decodes the pixels. Photoshop only stores a full composite when "Maximize Compatibility"
|
|
267
|
-
* is enabled; otherwise this is blank.
|
|
300
|
+
* is enabled; otherwise this is blank. Each call decodes again and returns new pixels, which
|
|
301
|
+
* aren't kept, so hold on to the result if you need it more than once.
|
|
268
302
|
*/
|
|
269
|
-
decode(): Promise<RGBAImage> {
|
|
270
|
-
return (this.#decoded ??= this.#decode());
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
async #decode(): Promise<RGBAImage> {
|
|
303
|
+
async decode(): Promise<RGBAImage> {
|
|
274
304
|
const header = this.#header;
|
|
275
305
|
const { width, height, channels: count } = header;
|
|
276
306
|
const model = colorModel(header, this.#resources);
|
|
277
307
|
const r = this.#reader.at(this.#reader.pos);
|
|
278
|
-
const planes = await readPlanes(r, r.bytes.length, count, width, height, header);
|
|
308
|
+
const planes = await readPlanes(r, r.uint16(), r.bytes.length, count, width, height, header);
|
|
279
309
|
|
|
280
310
|
const channels = new Map(planes.slice(0, model.colorCount).entries());
|
|
281
311
|
// A single extra channel is transparency; more than that are saved selections and spot colors.
|
|
@@ -283,8 +313,9 @@ export class CompositeImage {
|
|
|
283
313
|
return { width, height, data: toRgba(model, channels, width * height) };
|
|
284
314
|
}
|
|
285
315
|
|
|
286
|
-
|
|
287
|
-
|
|
316
|
+
/** Encodes `decode()` as a PNG, with the document's ICC profile when it's an RGB profile (see `options`). */
|
|
317
|
+
async toPng(options: ToPngOptions = {}): Promise<Uint8Array> {
|
|
318
|
+
return encodePng(await this.decode(), { iccProfile: rgbProfile(this.#resources(), options) });
|
|
288
319
|
}
|
|
289
320
|
}
|
|
290
321
|
|
|
@@ -293,7 +324,6 @@ export class LayerImage {
|
|
|
293
324
|
readonly #layer: Layer;
|
|
294
325
|
readonly #reader: Reader;
|
|
295
326
|
readonly #resources: () => Resources;
|
|
296
|
-
#decoded: Promise<RGBAImage> | undefined;
|
|
297
327
|
|
|
298
328
|
constructor(layer: Layer, reader: Reader, resources: () => Resources) {
|
|
299
329
|
this.#layer = layer;
|
|
@@ -314,12 +344,11 @@ export class LayerImage {
|
|
|
314
344
|
return this.#layer.mask !== undefined && this.#layer.channels.some((c) => c.id === -2);
|
|
315
345
|
}
|
|
316
346
|
|
|
317
|
-
/**
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
async #decode(): Promise<RGBAImage> {
|
|
347
|
+
/**
|
|
348
|
+
* Decodes the layer pixels. The mask is not applied; see `decodeMask()`. Like the composite,
|
|
349
|
+
* each call decodes again and the pixels aren't kept.
|
|
350
|
+
*/
|
|
351
|
+
async decode(): Promise<RGBAImage> {
|
|
323
352
|
const { header, width, height } = this.#layer;
|
|
324
353
|
const model = colorModel(header, this.#resources);
|
|
325
354
|
const planes = new Map<number, Uint8Array>();
|
|
@@ -338,7 +367,8 @@ export class LayerImage {
|
|
|
338
367
|
return { width: mask.width, height: mask.height, data: await readLayerChannel(this.#reader, channel, mask.width, mask.height, header) };
|
|
339
368
|
}
|
|
340
369
|
|
|
341
|
-
|
|
342
|
-
|
|
370
|
+
/** Encodes `decode()` as a PNG, with the document's ICC profile when it's an RGB profile (see `options`). */
|
|
371
|
+
async toPng(options: ToPngOptions = {}): Promise<Uint8Array> {
|
|
372
|
+
return encodePng(await this.decode(), { iccProfile: rgbProfile(this.#resources(), options) });
|
|
343
373
|
}
|
|
344
374
|
}
|
package/src/index.ts
CHANGED
|
@@ -9,9 +9,10 @@ export {
|
|
|
9
9
|
type ChannelInfo,
|
|
10
10
|
type GlobalMask,
|
|
11
11
|
type InfoBlock,
|
|
12
|
+
type LayerKind,
|
|
12
13
|
type Mask,
|
|
13
14
|
} from './layer.ts';
|
|
14
|
-
export type { LayerInfo } from './layer-info.ts';
|
|
15
|
+
export type { LayerInfo, PlacedLayer, Point } from './layer-info.ts';
|
|
15
16
|
export { descriptorColor } from './layer-styles.ts';
|
|
16
17
|
export type {
|
|
17
18
|
Bevel,
|
|
@@ -27,12 +28,23 @@ export type {
|
|
|
27
28
|
Shadow,
|
|
28
29
|
Stroke,
|
|
29
30
|
} from './layer-styles.ts';
|
|
30
|
-
export {
|
|
31
|
-
export {
|
|
32
|
-
|
|
31
|
+
export type { ShapeContent, VectorFill, VectorOrigination, VectorShape, VectorStroke } from './shapes.ts';
|
|
32
|
+
export {
|
|
33
|
+
TypeTool,
|
|
34
|
+
type RGBA,
|
|
35
|
+
type TextAlignment,
|
|
36
|
+
type TextBaseline,
|
|
37
|
+
type TextCaps,
|
|
38
|
+
type TextRun,
|
|
39
|
+
type Transform,
|
|
40
|
+
} from './type-tool.ts';
|
|
41
|
+
export { CompositeImage, LayerImage, type GrayImage, type RGBAImage, type ToPngOptions } from './image.ts';
|
|
42
|
+
export { encodePng, type Pixels, type PngOptions } from './png.ts';
|
|
43
|
+
export type { LinkedFile } from './linked-files.ts';
|
|
44
|
+
export { Pattern } from './patterns.ts';
|
|
33
45
|
export { Resources } from './resources.ts';
|
|
34
46
|
export type { Bounds, Guide, LayerComp, ResolutionInfo, ResourceBlock, SavedPath, Slice, Slices } from './resources.ts';
|
|
35
47
|
export type { Descriptor, DescriptorClass, UnitValue } from './descriptor.ts';
|
|
36
|
-
export type
|
|
48
|
+
export { pathToSvg, type PathPoint, type PathRecord } from './path-record.ts';
|
|
37
49
|
export { parseEngineData, type EngineDict, type EngineValue } from './engine-data.ts';
|
|
38
50
|
export type { SpaceColor } from './reader.ts';
|
package/src/layer-info.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { readLayerStyles } from './layer-styles.ts';
|
|
|
4
4
|
import { readPathRecords } from './path-record.ts';
|
|
5
5
|
import type { Header } from './psd.ts';
|
|
6
6
|
import type { Reader, SpaceColor } from './reader.ts';
|
|
7
|
+
import { readVectorFill, readVectorOrigination, readVectorStroke } from './shapes.ts';
|
|
7
8
|
import { readLegacyTypeTool, TypeTool } from './type-tool.ts';
|
|
8
9
|
|
|
9
10
|
interface Ctx {
|
|
@@ -340,6 +341,71 @@ function readEffectsLayer(r: Reader) {
|
|
|
340
341
|
return effects;
|
|
341
342
|
}
|
|
342
343
|
|
|
344
|
+
export interface Point {
|
|
345
|
+
x: number;
|
|
346
|
+
y: number;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** A smart object's source and placement. The raw descriptor, including the warp, is `data`. */
|
|
350
|
+
export interface PlacedLayer {
|
|
351
|
+
/** The source file's ID in the document's linked file data. Copies of a smart object share it. */
|
|
352
|
+
fileId: string;
|
|
353
|
+
/** The page of a multi-page source such as a PDF, from 1. */
|
|
354
|
+
page: number;
|
|
355
|
+
totalPages: number;
|
|
356
|
+
/**
|
|
357
|
+
* Where the content's corners are in the document, in pixels: top left, top right, bottom
|
|
358
|
+
* right, bottom left. Unlike the layer's bounds, these include transparent edges and follow
|
|
359
|
+
* rotation. The raw values are in `data.Trnf`.
|
|
360
|
+
*/
|
|
361
|
+
corners: [Point, Point, Point, Point];
|
|
362
|
+
/** The corners including any perspective or distort transform. Undefined in older files. */
|
|
363
|
+
nonAffineCorners: [Point, Point, Point, Point] | undefined;
|
|
364
|
+
/** The content's size, in its own pixels. */
|
|
365
|
+
size: { width: number; height: number };
|
|
366
|
+
/** The content's resolution, in pixels per inch. */
|
|
367
|
+
resolution: number;
|
|
368
|
+
/**
|
|
369
|
+
* Degrees clockwise, from the angle of the top edge. Only meaningful without skew or perspective.
|
|
370
|
+
*/
|
|
371
|
+
rotation: number;
|
|
372
|
+
/**
|
|
373
|
+
* The corners' size relative to `size`. A flip makes `y` negative (a horizontal flip is a
|
|
374
|
+
* 180° rotation plus a vertical flip). Photoshop's W and H percentages are relative to the
|
|
375
|
+
* content's physical size instead, so they differ when `resolution` isn't the document's.
|
|
376
|
+
*/
|
|
377
|
+
scale: { x: number; y: number };
|
|
378
|
+
/** The raw descriptor, for anything not covered above, such as the `warp`. */
|
|
379
|
+
data: Descriptor;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
type Corners = PlacedLayer['corners'];
|
|
383
|
+
|
|
384
|
+
const corners = (values: number[]) =>
|
|
385
|
+
[0, 2, 4, 6].map((i) => ({ x: values[i]!, y: values[i + 1]! })) as Corners;
|
|
386
|
+
|
|
387
|
+
/** Normalizes a smart object's descriptor. */
|
|
388
|
+
export function readPlacedLayer(d: Descriptor): PlacedLayer {
|
|
389
|
+
if (d.Trnf?.length !== 8) throw new Error('Smart object descriptor has no transform');
|
|
390
|
+
const [topLeft, topRight, , bottomLeft] = corners(d.Trnf);
|
|
391
|
+
const top = { x: topRight.x - topLeft.x, y: topRight.y - topLeft.y };
|
|
392
|
+
const left = { x: bottomLeft.x - topLeft.x, y: bottomLeft.y - topLeft.y };
|
|
393
|
+
const size = { width: d['Sz '].Wdth as number, height: d['Sz '].Hght as number };
|
|
394
|
+
const flip = Math.sign(top.x * left.y - top.y * left.x) || 1;
|
|
395
|
+
return {
|
|
396
|
+
fileId: d.Idnt,
|
|
397
|
+
page: d.PgNm,
|
|
398
|
+
totalPages: d.totalPages,
|
|
399
|
+
corners: corners(d.Trnf),
|
|
400
|
+
nonAffineCorners: d.nonAffineTransform && corners(d.nonAffineTransform),
|
|
401
|
+
size,
|
|
402
|
+
resolution: d.Rslt.value,
|
|
403
|
+
rotation: (Math.atan2(top.y, top.x) * 180) / Math.PI,
|
|
404
|
+
scale: { x: Math.hypot(top.x, top.y) / size.width, y: (flip * Math.hypot(left.x, left.y)) / size.height },
|
|
405
|
+
data: d,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
343
409
|
function readMetadata(r: Reader) {
|
|
344
410
|
const metadata: { layerComp?: Descriptor } = {};
|
|
345
411
|
const count = r.int32();
|
|
@@ -464,7 +530,6 @@ const LAYER_INFO = {
|
|
|
464
530
|
return { enabled: value > 0, mode: value === 1 ? ('shallow' as const) : value === 2 ? ('deep' as const) : undefined };
|
|
465
531
|
},
|
|
466
532
|
},
|
|
467
|
-
layerEffects: { keys: ['lfxs'], parse: descriptorAfter(8) },
|
|
468
533
|
layerId: { keys: ['lyid'], parse: (r: Reader) => r.int32() },
|
|
469
534
|
layerMaskAsGlobalMask: { keys: ['lmgm'], parse: flag },
|
|
470
535
|
/** Minimum Photoshop version needed to read the layer, times 10 (70 = 7.0). */
|
|
@@ -498,12 +563,12 @@ const LAYER_INFO = {
|
|
|
498
563
|
return { isFolder: code === 1 || code === 2, isHidden: code === 3 };
|
|
499
564
|
},
|
|
500
565
|
},
|
|
501
|
-
/** Layer styles (drop shadow, stroke, etc.). */
|
|
502
|
-
objectEffects: { keys: ['lfx2', 'lmfx'], parse: (r: Reader) => readLayerStyles(descriptorAfter(8)(r)) },
|
|
566
|
+
/** Layer styles (drop shadow, stroke, etc.). Photoshop stores a group's styles in `lfxs`. */
|
|
567
|
+
objectEffects: { keys: ['lfx2', 'lmfx', 'lfxs'], parse: (r: Reader) => readLayerStyles(descriptorAfter(8)(r)) },
|
|
503
568
|
patternFill: { keys: ['PtFl'], parse: descriptorAfter(4) },
|
|
504
569
|
photoFilter: { keys: ['phfl'], parse: readPhotoFilter },
|
|
505
|
-
/** Smart object data
|
|
506
|
-
placedLayer: { keys: ['SoLd', 'SoLE'], parse: descriptorAfter(12) },
|
|
570
|
+
/** Smart object data: its normalized source and placement, with the raw descriptor as `data`. */
|
|
571
|
+
placedLayer: { keys: ['SoLd', 'SoLE'], parse: (r: Reader) => readPlacedLayer(descriptorAfter(12)(r)) },
|
|
507
572
|
posterize: { keys: ['post'], parse: (r: Reader) => r.int16() },
|
|
508
573
|
referencePoint: { keys: ['fxrp'], parse: (r: Reader) => ({ x: r.float64(), y: r.float64() }) },
|
|
509
574
|
sectionDivider: { keys: ['lsct'], parse: readDivider },
|
|
@@ -535,9 +600,12 @@ const LAYER_INFO = {
|
|
|
535
600
|
},
|
|
536
601
|
},
|
|
537
602
|
vectorMaskAsGlobalMask: { keys: ['vmgm'], parse: flag },
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
603
|
+
/** Live shape properties: `shapes`, one per shape in the layer, and the raw descriptor as `data`. */
|
|
604
|
+
vectorOrigination: { keys: ['vogk'], parse: (r: Reader) => readVectorOrigination(descriptorAfter(8)(r)) },
|
|
605
|
+
/** A shape layer's stroke, and whether its fill and stroke are shown, with the raw descriptor as `data`. */
|
|
606
|
+
vectorStroke: { keys: ['vstk'], parse: (r: Reader) => readVectorStroke(descriptorAfter(4)(r)) },
|
|
607
|
+
/** A shape layer's fill: its `color`, `gradient` or `pattern`, with the raw descriptor as `data`. */
|
|
608
|
+
vectorStrokeContent: { keys: ['vscg'], parse: (r: Reader) => readVectorFill(descriptorAfter(8)(r)) },
|
|
541
609
|
vibrance: {
|
|
542
610
|
keys: ['vibA'],
|
|
543
611
|
parse: (r: Reader) => {
|
package/src/layer-styles.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { BlendMode } from './layer.ts';
|
|
|
4
4
|
|
|
5
5
|
export type RGB = [number, number, number];
|
|
6
6
|
|
|
7
|
-
/** Layer styles (the `lfx2`/`lmfx` block). Photoshop CC allows several of some effects per layer. */
|
|
7
|
+
/** Layer styles (the `lfx2`/`lmfx` block, or `lfxs` for groups). Photoshop CC allows several of some effects per layer. */
|
|
8
8
|
export interface LayerStyles {
|
|
9
9
|
/** The master "show effects" switch. */
|
|
10
10
|
enabled: boolean;
|
|
@@ -36,6 +36,7 @@ export interface Shadow extends Effect {
|
|
|
36
36
|
color: RGB | undefined;
|
|
37
37
|
/** Degrees. */
|
|
38
38
|
angle: number;
|
|
39
|
+
/** Use the document's `resources.globalAngle` instead of `angle`. */
|
|
39
40
|
useGlobalLight: boolean;
|
|
40
41
|
distance: number;
|
|
41
42
|
/** "Spread" for drop shadows, "choke" for inner shadows, in pixels. */
|
|
@@ -78,6 +79,7 @@ export interface Bevel {
|
|
|
78
79
|
soften: number;
|
|
79
80
|
angle: number;
|
|
80
81
|
altitude: number;
|
|
82
|
+
/** Use the document's `resources.globalAngle` and `globalAltitude` instead of `angle` and `altitude`. */
|
|
81
83
|
useGlobalLight: boolean;
|
|
82
84
|
highlight: { blendMode: BlendMode | string | undefined; color: RGB | undefined; opacity: number };
|
|
83
85
|
shadow: { blendMode: BlendMode | string | undefined; color: RGB | undefined; opacity: number };
|
|
@@ -179,14 +181,14 @@ const BLEND_MODES: Record<string, BlendMode> = {
|
|
|
179
181
|
|
|
180
182
|
/** Unit values (`{ value }`) and plain numbers as a number. */
|
|
181
183
|
const num = (v: any): number => (typeof v === 'object' && v !== null ? v.value : (v ?? 0));
|
|
182
|
-
const percent = (v: any) => num(v) / 100;
|
|
183
|
-
const enumValue = (v: any): string | undefined => v?.value?.trim();
|
|
184
|
-
const blendMode = (v: any) => {
|
|
184
|
+
export const percent = (v: any) => num(v) / 100;
|
|
185
|
+
export const enumValue = (v: any): string | undefined => v?.value?.trim();
|
|
186
|
+
export const blendMode = (v: any) => {
|
|
185
187
|
const value = enumValue(v);
|
|
186
188
|
return value === undefined ? undefined : (BLEND_MODES[value] ?? value);
|
|
187
189
|
};
|
|
188
190
|
const contour = (v: any): string | undefined => v?.['Nm '];
|
|
189
|
-
const pattern = (v: any) => (v ? { name: v['Nm '] as string, id: v.Idnt as string } : undefined);
|
|
191
|
+
export const pattern = (v: any) => (v ? { name: v['Nm '] as string, id: v.Idnt as string } : undefined);
|
|
190
192
|
|
|
191
193
|
/** Converts a descriptor color to RGB. */
|
|
192
194
|
export function descriptorColor(c: Descriptor | undefined): RGB | undefined {
|
|
@@ -220,7 +222,7 @@ export function descriptorColor(c: Descriptor | undefined): RGB | undefined {
|
|
|
220
222
|
}
|
|
221
223
|
}
|
|
222
224
|
|
|
223
|
-
function gradient(g: Descriptor | undefined): Gradient | undefined {
|
|
225
|
+
export function gradient(g: Descriptor | undefined): Gradient | undefined {
|
|
224
226
|
if (!g) return undefined;
|
|
225
227
|
const stop = (s: Descriptor) => ({ location: s.Lctn / 4096, midpoint: s.Mdpn / 100 });
|
|
226
228
|
return {
|
package/src/layer.ts
CHANGED
|
@@ -59,6 +59,18 @@ export interface Mask {
|
|
|
59
59
|
relative: boolean;
|
|
60
60
|
disabled: boolean;
|
|
61
61
|
invert: boolean;
|
|
62
|
+
/** The user (pixel) mask's density, 0 to 1. 1 unless set in the Properties panel. */
|
|
63
|
+
density: number;
|
|
64
|
+
/** The user mask's feather, in pixels. */
|
|
65
|
+
feather: number;
|
|
66
|
+
/**
|
|
67
|
+
* The vector mask's density, 0 to 1. Photoshop stores it here, in the layer mask record, so it's
|
|
68
|
+
* only available when the layer has one: setting a vector mask's density or feather makes
|
|
69
|
+
* Photoshop write one.
|
|
70
|
+
*/
|
|
71
|
+
vectorDensity: number;
|
|
72
|
+
/** The vector mask's feather, in pixels. */
|
|
73
|
+
vectorFeather: number;
|
|
62
74
|
}
|
|
63
75
|
|
|
64
76
|
export interface BlendingRange {
|
|
@@ -87,8 +99,17 @@ export interface GlobalMask {
|
|
|
87
99
|
kind: number;
|
|
88
100
|
}
|
|
89
101
|
|
|
102
|
+
/**
|
|
103
|
+
* What a layer is, as shown in Photoshop's layers panel. See `Layer.kind` for how it's decided.
|
|
104
|
+
* Video and 3D layers are `'pixel'`.
|
|
105
|
+
*/
|
|
106
|
+
export type LayerKind = 'group' | 'text' | 'smartObject' | 'adjustment' | 'shape' | 'fill' | 'pixel';
|
|
107
|
+
|
|
108
|
+
const ADJUSTMENT_KEYS = ['brit', 'CgEd', 'levl', 'curv', 'expA', 'vibA', 'hue ', 'hue2', 'blnc', 'blwh', 'phfl', 'mixr', 'clrL', 'nvrt', 'post', 'thrs', 'selc', 'grdm'];
|
|
109
|
+
const FILL_KEYS = ['SoCo', 'GdFl', 'PtFl'];
|
|
110
|
+
|
|
90
111
|
/** Tagged block keys whose length is 8 bytes in PSB files. */
|
|
91
|
-
const BIG_KEYS = new Set(['LMsk', 'Lr16', 'Lr32', 'Layr', 'Mt16', 'Mt32', 'Mtrn', 'Alph', 'FMsk', 'lnk2', 'FEid', 'FXid', 'PxSD']);
|
|
112
|
+
const BIG_KEYS = new Set(['LMsk', 'Lr16', 'Lr32', 'Layr', 'Mt16', 'Mt32', 'Mtrn', 'Alph', 'FMsk', 'lnk2', 'lnk3', 'lnkE', 'FEid', 'FXid', 'PxSD']);
|
|
92
113
|
|
|
93
114
|
export const readBlockLength = (r: Reader, header: Header, key: string) =>
|
|
94
115
|
header.isBig && BIG_KEYS.has(key) ? r.int64() : r.uint32();
|
|
@@ -147,7 +168,7 @@ export class Layer {
|
|
|
147
168
|
const extraLength = r.uint32();
|
|
148
169
|
const end = r.pos + extraLength;
|
|
149
170
|
|
|
150
|
-
this.mask = readMask(r);
|
|
171
|
+
this.mask = readMask(r, this.channels.some((c) => c.id === -3));
|
|
151
172
|
this.blendingRanges = readBlendingRanges(r);
|
|
152
173
|
|
|
153
174
|
const nameLength = ((r.uint8() + 4) & ~3) - 1; // padded to a multiple of 4, including the length byte
|
|
@@ -208,13 +229,37 @@ export class Layer {
|
|
|
208
229
|
return divider ? divider.isHidden : this.name === '</Layer group>';
|
|
209
230
|
}
|
|
210
231
|
|
|
232
|
+
/**
|
|
233
|
+
* What the layer is, from the blocks it has, checked in this order:
|
|
234
|
+
*
|
|
235
|
+
* 1. `'group'`: a group's start or end marker, including artboards.
|
|
236
|
+
* 2. `'text'`: has type tool data.
|
|
237
|
+
* 3. `'smartObject'`: has placed layer data, embedded or linked.
|
|
238
|
+
* 4. `'adjustment'`: has adjustment settings (levels, curves...), even if it also has a vector mask.
|
|
239
|
+
* 5. `'shape'`: has a vector mask and fill content. This includes a fill layer with a vector mask,
|
|
240
|
+
* which is how Photoshop has always stored shapes, so the two can't be told apart.
|
|
241
|
+
* 6. `'fill'`: a solid color, gradient or pattern fill layer.
|
|
242
|
+
* 7. `'pixel'`: anything else, including pixel layers with a vector mask drawn with a shape tool.
|
|
243
|
+
*/
|
|
244
|
+
get kind(): LayerKind {
|
|
245
|
+
const has = (...keys: string[]) => this.infoBlocks.some((b) => keys.includes(b.key));
|
|
246
|
+
if (this.isFolder || this.isFolderEnd) return 'group';
|
|
247
|
+
if (has('TySh', 'tySh')) return 'text';
|
|
248
|
+
if (has('SoLd', 'SoLE', 'PlLd', 'plLd')) return 'smartObject';
|
|
249
|
+
if (has(...ADJUSTMENT_KEYS)) return 'adjustment';
|
|
250
|
+
const fill = has(...FILL_KEYS);
|
|
251
|
+
if ((fill || has('vscg')) && has('vmsk', 'vsms')) return 'shape';
|
|
252
|
+
return fill ? 'fill' : 'pixel';
|
|
253
|
+
}
|
|
254
|
+
|
|
211
255
|
/** The layer's pixels. Decoding happens on demand. */
|
|
212
256
|
get image(): LayerImage {
|
|
213
257
|
return (this.#image ??= new LayerImage(this, this.#reader, this.#resources));
|
|
214
258
|
}
|
|
215
259
|
}
|
|
216
260
|
|
|
217
|
-
|
|
261
|
+
/** `hasRealMask`: the layer has a real user mask channel (-3), whose fields precede the parameters. */
|
|
262
|
+
function readMask(r: Reader, hasRealMask: boolean): Mask | undefined {
|
|
218
263
|
const size = r.uint32();
|
|
219
264
|
if (size === 0) return undefined;
|
|
220
265
|
const end = r.pos + size;
|
|
@@ -224,6 +269,19 @@ function readMask(r: Reader): Mask | undefined {
|
|
|
224
269
|
const right = r.int32();
|
|
225
270
|
const defaultColor = r.uint8();
|
|
226
271
|
const flags = r.uint8();
|
|
272
|
+
// Photoshop only writes parameters that differ from these defaults.
|
|
273
|
+
const params = { density: 1, feather: 0, vectorDensity: 1, vectorFeather: 0 };
|
|
274
|
+
if (flags & 0x10) {
|
|
275
|
+
// The spec puts the parameters first, but Photoshop writes the real user mask's flags,
|
|
276
|
+
// default color and rectangle before them. Its size can't tell them apart, the channel can.
|
|
277
|
+
if (hasRealMask && size >= 36) r.skip(18);
|
|
278
|
+
const present = r.uint8();
|
|
279
|
+
if (present & 0x01) params.density = r.uint8() / 255;
|
|
280
|
+
if (present & 0x02) params.feather = r.float64();
|
|
281
|
+
if (present & 0x04) params.vectorDensity = r.uint8() / 255;
|
|
282
|
+
if (present & 0x08) params.vectorFeather = r.float64();
|
|
283
|
+
if (r.pos > end) throw new Error(`Layer mask parameters overrun the ${size} byte mask record`);
|
|
284
|
+
}
|
|
227
285
|
r.seek(end);
|
|
228
286
|
return {
|
|
229
287
|
top,
|
|
@@ -236,6 +294,7 @@ function readMask(r: Reader): Mask | undefined {
|
|
|
236
294
|
relative: (flags & 0x01) > 0,
|
|
237
295
|
disabled: (flags & 0x02) > 0,
|
|
238
296
|
invert: (flags & 0x04) > 0,
|
|
297
|
+
...params,
|
|
239
298
|
};
|
|
240
299
|
}
|
|
241
300
|
|
|
@@ -257,6 +316,8 @@ export interface LayerSection {
|
|
|
257
316
|
globalMask: GlobalMask | undefined;
|
|
258
317
|
/** The first alpha channel of the composite image holds the merged transparency. */
|
|
259
318
|
mergedAlpha: boolean;
|
|
319
|
+
/** Document-wide tagged blocks after the global mask, such as linked files and patterns. */
|
|
320
|
+
infoBlocks: InfoBlock[];
|
|
260
321
|
}
|
|
261
322
|
|
|
262
323
|
/**
|
|
@@ -264,7 +325,7 @@ export interface LayerSection {
|
|
|
264
325
|
* `resources` is only read when decoding indexed color layers, which need the color table.
|
|
265
326
|
*/
|
|
266
327
|
export function readLayerSection(r: Reader, header: Header, resources: () => Resources): LayerSection {
|
|
267
|
-
const section: LayerSection = { layers: [], globalMask: undefined, mergedAlpha: false };
|
|
328
|
+
const section: LayerSection = { layers: [], globalMask: undefined, mergedAlpha: false, infoBlocks: [] };
|
|
268
329
|
const length = header.isBig ? r.int64() : r.uint32();
|
|
269
330
|
const end = r.pos + length;
|
|
270
331
|
if (length === 0) return section;
|
|
@@ -292,14 +353,26 @@ export function readLayerSection(r: Reader, header: Header, resources: () => Res
|
|
|
292
353
|
readLayers(pad2(header.isBig ? r.int64() : r.uint32()));
|
|
293
354
|
section.globalMask = readGlobalMask(r);
|
|
294
355
|
|
|
295
|
-
// 16 and 32-bit documents store their layers in
|
|
356
|
+
// 16 and 32-bit documents store their layers in an Lr16 or Lr32 block after the global mask.
|
|
357
|
+
// The main section may hold 8-bit compatibility copies, which these replace. Some files use a
|
|
358
|
+
// Layr block instead, and some pad the blocks with zero bytes.
|
|
296
359
|
while (r.pos + 12 <= end) {
|
|
360
|
+
if (r.bytes[r.pos] === 0) {
|
|
361
|
+
r.skip(1);
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
297
364
|
const sig = r.ascii(4);
|
|
298
365
|
if (sig !== '8BIM' && sig !== '8B64') break;
|
|
299
366
|
const key = r.ascii(4);
|
|
300
367
|
const blockLength = pad2(readBlockLength(r, header, key));
|
|
301
368
|
const blockEnd = r.pos + blockLength;
|
|
302
|
-
|
|
369
|
+
section.infoBlocks.push({ key, offset: r.pos, length: blockLength });
|
|
370
|
+
if (key === `Lr${header.depth}`) {
|
|
371
|
+
section.layers = [];
|
|
372
|
+
readLayers(blockLength);
|
|
373
|
+
} else if (key === 'Layr' && section.layers.length === 0) {
|
|
374
|
+
readLayers(blockLength);
|
|
375
|
+
}
|
|
303
376
|
r.seek(blockEnd);
|
|
304
377
|
}
|
|
305
378
|
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { readDescriptor, type Descriptor } from './descriptor.ts';
|
|
2
|
+
import type { Reader } from './reader.ts';
|
|
3
|
+
|
|
4
|
+
const TYPES = { liFD: 'embedded', liFE: 'external', liFA: 'alias' } as const;
|
|
5
|
+
|
|
6
|
+
/** A file placed in the document as a smart object, from the `lnk2`, `lnk3`, `lnkD` or `lnkE` blocks. */
|
|
7
|
+
export interface LinkedFile {
|
|
8
|
+
/** The unique ID that smart object layers refer to in `info.placedLayer.fileId`. */
|
|
9
|
+
id: string;
|
|
10
|
+
/** The original file name. */
|
|
11
|
+
name: string;
|
|
12
|
+
/** Whether the file is embedded in the document, or a link to an external file or alias. */
|
|
13
|
+
type: (typeof TYPES)[keyof typeof TYPES];
|
|
14
|
+
/** The file type code, such as `'8BPB'` for PSD and PSB or `'png '`. Can be empty. */
|
|
15
|
+
fileType: string;
|
|
16
|
+
/** The creator code. Can be empty. */
|
|
17
|
+
creator: string;
|
|
18
|
+
version: number;
|
|
19
|
+
/**
|
|
20
|
+
* The file contents, for embedded files and external files that store a copy. Embedded PSD and
|
|
21
|
+
* PSB files can be opened with `new PSD(data)`.
|
|
22
|
+
*/
|
|
23
|
+
data?: Uint8Array;
|
|
24
|
+
/** For external files: where the file was, with keys such as `fullPath`, `relPath` and `originalPath`. */
|
|
25
|
+
location?: Descriptor;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Reads the linked files in a `lnk2`, `lnk3`, `lnkD` or `lnkE` block. The data is a view into the file, not a copy. */
|
|
29
|
+
export function readLinkedFiles(r: Reader, end: number): LinkedFile[] {
|
|
30
|
+
const files: LinkedFile[] = [];
|
|
31
|
+
// Each file is a length-prefixed record padded to 4 bytes. Some blocks end with padding too short to hold one.
|
|
32
|
+
while (r.pos + 8 <= end) {
|
|
33
|
+
const length = r.int64();
|
|
34
|
+
const next = r.pos + ((length + 3) & ~3);
|
|
35
|
+
if (r.pos + length > end) throw new Error(`Linked file of ${length} bytes overruns its block`);
|
|
36
|
+
|
|
37
|
+
const key = r.ascii(4);
|
|
38
|
+
const type = TYPES[key as keyof typeof TYPES];
|
|
39
|
+
if (!type) throw new Error(`Unknown linked file type '${key}'`);
|
|
40
|
+
const version = r.uint32();
|
|
41
|
+
const id = r.pascal();
|
|
42
|
+
const name = r.unicode();
|
|
43
|
+
const fileType = r.ascii(4);
|
|
44
|
+
const creator = r.ascii(4);
|
|
45
|
+
const dataLength = r.int64();
|
|
46
|
+
if (r.bool()) {
|
|
47
|
+
r.skip(4); // descriptor version
|
|
48
|
+
readDescriptor(r); // open file descriptor
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const file: LinkedFile = { id, name, type, fileType, creator, version };
|
|
52
|
+
if (type === 'external') {
|
|
53
|
+
r.skip(4); // descriptor version
|
|
54
|
+
file.location = readDescriptor(r);
|
|
55
|
+
if (version > 3) r.skip(16); // modification time: year (4), month, day, hour, minute (1 each), seconds (8)
|
|
56
|
+
r.skip(8); // the external file's size
|
|
57
|
+
if (version >= 2 && dataLength > 0) file.data = r.bytesView(dataLength);
|
|
58
|
+
} else if (type === 'embedded') {
|
|
59
|
+
file.data = r.bytesView(dataLength);
|
|
60
|
+
}
|
|
61
|
+
// Version 5+ fields (child document ID, modification time, lock state) aren't read.
|
|
62
|
+
files.push(file);
|
|
63
|
+
r.seek(next);
|
|
64
|
+
}
|
|
65
|
+
return files;
|
|
66
|
+
}
|
package/src/nodes.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { LayerImage } from './image.ts';
|
|
2
|
-
import type { BlendMode, Layer } from './layer.ts';
|
|
2
|
+
import type { BlendMode, Layer, LayerKind } from './layer.ts';
|
|
3
3
|
import type { LayerInfo } from './layer-info.ts';
|
|
4
|
+
import type { LinkedFile } from './linked-files.ts';
|
|
4
5
|
import type { PSD } from './psd.ts';
|
|
5
6
|
import type { LayerComp } from './resources.ts';
|
|
6
7
|
|
|
@@ -180,6 +181,11 @@ abstract class LayerBackedNode extends BaseNode {
|
|
|
180
181
|
return this.layer.info;
|
|
181
182
|
}
|
|
182
183
|
|
|
184
|
+
/** `'group'`, `'text'`, `'shape'`, `'pixel'`... See `Layer.kind` for how it's decided. */
|
|
185
|
+
get kind(): LayerKind {
|
|
186
|
+
return this.layer.kind;
|
|
187
|
+
}
|
|
188
|
+
|
|
183
189
|
/** Visible, accounting for clipping masks and the tree's layer comp. */
|
|
184
190
|
get visible(): boolean {
|
|
185
191
|
if (this.layer.clipped && this.clippingMask?.visible === false) return false;
|
|
@@ -272,6 +278,7 @@ abstract class LayerBackedNode extends BaseNode {
|
|
|
272
278
|
toJSON() {
|
|
273
279
|
return {
|
|
274
280
|
type: this.type,
|
|
281
|
+
kind: this.kind,
|
|
275
282
|
id: this.id,
|
|
276
283
|
name: this.name,
|
|
277
284
|
visible: this.visible,
|
|
@@ -317,6 +324,12 @@ export class LayerNode extends LayerBackedNode {
|
|
|
317
324
|
return this.layer.image;
|
|
318
325
|
}
|
|
319
326
|
|
|
327
|
+
/** For smart object layers, the placed file from `psd.linkedFiles`. */
|
|
328
|
+
get linkedFile(): LinkedFile | undefined {
|
|
329
|
+
const id = this.layer.info.placedLayer?.fileId;
|
|
330
|
+
return id === undefined ? undefined : this.root.psd.linkedFiles.find((f) => f.id === id);
|
|
331
|
+
}
|
|
332
|
+
|
|
320
333
|
get isEmpty(): boolean {
|
|
321
334
|
return this.width === 0 || this.height === 0;
|
|
322
335
|
}
|
|
@@ -347,13 +360,14 @@ export class RootNode extends BaseNode {
|
|
|
347
360
|
const stack: Array<RootNode | GroupNode> = [];
|
|
348
361
|
for (const layer of psd.layers) {
|
|
349
362
|
if (layer.isFolder) {
|
|
363
|
+
const group = new GroupNode(layer, current);
|
|
364
|
+
current.children.push(group);
|
|
350
365
|
stack.push(current);
|
|
351
|
-
current =
|
|
366
|
+
current = group;
|
|
352
367
|
} else if (layer.isFolderEnd) {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
current = parent;
|
|
368
|
+
// Files from some editors have unbalanced markers. Rather than fail, a stray end marker is
|
|
369
|
+
// ignored, and groups still open at the bottom of the list end there.
|
|
370
|
+
current = stack.pop() ?? current;
|
|
357
371
|
} else {
|
|
358
372
|
current.children.push(new LayerNode(layer, current));
|
|
359
373
|
}
|