psd 3.4.0 → 4.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.
Files changed (216) hide show
  1. package/README.md +196 -149
  2. package/dist/descriptor.d.ts +20 -0
  3. package/dist/descriptor.d.ts.map +1 -0
  4. package/dist/descriptor.js +114 -0
  5. package/dist/descriptor.js.map +1 -0
  6. package/dist/engine-data.d.ts +11 -0
  7. package/dist/engine-data.d.ts.map +1 -0
  8. package/dist/engine-data.js +82 -0
  9. package/dist/engine-data.js.map +1 -0
  10. package/dist/image.d.ts +52 -0
  11. package/dist/image.d.ts.map +1 -0
  12. package/dist/image.js +301 -0
  13. package/dist/image.js.map +1 -0
  14. package/dist/index.d.ts +16 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +10 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/layer-info.d.ts +494 -0
  19. package/dist/layer-info.d.ts.map +1 -0
  20. package/dist/layer-info.js +529 -0
  21. package/dist/layer-info.js.map +1 -0
  22. package/dist/layer-styles.d.ts +160 -0
  23. package/dist/layer-styles.d.ts.map +1 -0
  24. package/dist/layer-styles.js +183 -0
  25. package/dist/layer-styles.js.map +1 -0
  26. package/dist/layer.d.ts +143 -0
  27. package/dist/layer.d.ts.map +1 -0
  28. package/dist/layer.js +249 -0
  29. package/dist/layer.js.map +1 -0
  30. package/dist/nodes.d.ts +233 -0
  31. package/dist/nodes.d.ts.map +1 -0
  32. package/dist/nodes.js +326 -0
  33. package/dist/nodes.js.map +1 -0
  34. package/dist/path-record.d.ts +34 -0
  35. package/dist/path-record.d.ts.map +1 -0
  36. package/dist/path-record.js +44 -0
  37. package/dist/path-record.js.map +1 -0
  38. package/dist/png.d.ts +10 -0
  39. package/dist/png.d.ts.map +1 -0
  40. package/dist/png.js +85 -0
  41. package/dist/png.js.map +1 -0
  42. package/dist/psd.d.ts +49 -0
  43. package/dist/psd.d.ts.map +1 -0
  44. package/dist/psd.js +106 -0
  45. package/dist/psd.js.map +1 -0
  46. package/dist/reader.d.ts +41 -0
  47. package/dist/reader.d.ts.map +1 -0
  48. package/dist/reader.js +100 -0
  49. package/dist/reader.js.map +1 -0
  50. package/dist/resources.d.ts +105 -0
  51. package/dist/resources.d.ts.map +1 -0
  52. package/dist/resources.js +173 -0
  53. package/dist/resources.js.map +1 -0
  54. package/dist/type-tool.d.ts +142 -0
  55. package/dist/type-tool.d.ts.map +1 -0
  56. package/dist/type-tool.js +222 -0
  57. package/dist/type-tool.js.map +1 -0
  58. package/package.json +26 -32
  59. package/src/descriptor.ts +141 -0
  60. package/src/engine-data.ts +86 -0
  61. package/src/image.ts +338 -0
  62. package/src/index.ts +38 -0
  63. package/src/layer-info.ts +578 -0
  64. package/src/layer-styles.ts +339 -0
  65. package/src/layer.ts +334 -0
  66. package/src/nodes.ts +411 -0
  67. package/src/path-record.ts +69 -0
  68. package/src/png.ts +92 -0
  69. package/src/psd.ts +133 -0
  70. package/src/reader.ts +125 -0
  71. package/src/resources.ts +273 -0
  72. package/src/type-tool.ts +270 -0
  73. package/.travis.yml +0 -5
  74. package/Cakefile +0 -61
  75. package/DEVELOPMENT.md +0 -27
  76. package/bower.json +0 -26
  77. package/docs/docco.css +0 -284
  78. package/docs/lib/psd/blend_mode.coffee.html +0 -72
  79. package/docs/lib/psd/channel_image.coffee.html +0 -81
  80. package/docs/lib/psd/color.coffee.html +0 -13
  81. package/docs/lib/psd/descriptor.coffee.html +0 -173
  82. package/docs/lib/psd/file.coffee.html +0 -78
  83. package/docs/lib/psd/header.coffee.html +0 -71
  84. package/docs/lib/psd/image.coffee.html +0 -94
  85. package/docs/lib/psd/image_export.coffee.html +0 -5
  86. package/docs/lib/psd/image_exports/png.coffee.html +0 -19
  87. package/docs/lib/psd/image_format.coffee.html +0 -8
  88. package/docs/lib/psd/image_formats/layer_raw.coffee.html +0 -9
  89. package/docs/lib/psd/image_formats/layer_rle.coffee.html +0 -10
  90. package/docs/lib/psd/image_formats/raw.coffee.html +0 -6
  91. package/docs/lib/psd/image_formats/rle.coffee.html +0 -37
  92. package/docs/lib/psd/image_mode.coffee.html +0 -7
  93. package/docs/lib/psd/image_modes/cmyk.coffee.html +0 -36
  94. package/docs/lib/psd/image_modes/greyscale.coffee.html +0 -17
  95. package/docs/lib/psd/image_modes/rgb.coffee.html +0 -32
  96. package/docs/lib/psd/init.coffee.html +0 -22
  97. package/docs/lib/psd/layer/blend_modes.coffee.html +0 -22
  98. package/docs/lib/psd/layer/blending_ranges.coffee.html +0 -29
  99. package/docs/lib/psd/layer/channel_image.coffee.html +0 -13
  100. package/docs/lib/psd/layer/helpers.coffee.html +0 -19
  101. package/docs/lib/psd/layer/info.coffee.html +0 -69
  102. package/docs/lib/psd/layer/mask.coffee.html +0 -11
  103. package/docs/lib/psd/layer/name.coffee.html +0 -15
  104. package/docs/lib/psd/layer/position_channels.coffee.html +0 -24
  105. package/docs/lib/psd/layer.coffee.html +0 -64
  106. package/docs/lib/psd/layer_info/blend_clipping_elements.coffee.html +0 -11
  107. package/docs/lib/psd/layer_info/blend_interior_elements.coffee.html +0 -11
  108. package/docs/lib/psd/layer_info/fill_opacity.coffee.html +0 -10
  109. package/docs/lib/psd/layer_info/gradient_fill.coffee.html +0 -12
  110. package/docs/lib/psd/layer_info/layer_id.coffee.html +0 -10
  111. package/docs/lib/psd/layer_info/layer_name_source.coffee.html +0 -10
  112. package/docs/lib/psd/layer_info/legacy_typetool.coffee.html +0 -82
  113. package/docs/lib/psd/layer_info/locked.coffee.html +0 -24
  114. package/docs/lib/psd/layer_info/metadata.coffee.html +0 -30
  115. package/docs/lib/psd/layer_info/nested_section_divider.coffee.html +0 -23
  116. package/docs/lib/psd/layer_info/object_effects.coffee.html +0 -12
  117. package/docs/lib/psd/layer_info/section_divider.coffee.html +0 -41
  118. package/docs/lib/psd/layer_info/solid_color.coffee.html +0 -24
  119. package/docs/lib/psd/layer_info/typetool.coffee.html +0 -121
  120. package/docs/lib/psd/layer_info/unicode_name.coffee.html +0 -14
  121. package/docs/lib/psd/layer_info/vector_mask.coffee.html +0 -37
  122. package/docs/lib/psd/layer_info/vector_origination.coffee.html +0 -12
  123. package/docs/lib/psd/layer_info/vector_stroke.coffee.html +0 -12
  124. package/docs/lib/psd/layer_info/vector_stroke_content.coffee.html +0 -12
  125. package/docs/lib/psd/layer_info.coffee.html +0 -11
  126. package/docs/lib/psd/layer_mask.coffee.html +0 -73
  127. package/docs/lib/psd/lazy_execute.coffee.html +0 -80
  128. package/docs/lib/psd/mask.coffee.html +0 -47
  129. package/docs/lib/psd/node.coffee.html +0 -100
  130. package/docs/lib/psd/nodes/ancestry.coffee.html +0 -47
  131. package/docs/lib/psd/nodes/build_preview.coffee.html +0 -6
  132. package/docs/lib/psd/nodes/group.coffee.html +0 -19
  133. package/docs/lib/psd/nodes/layer.coffee.html +0 -17
  134. package/docs/lib/psd/nodes/root.coffee.html +0 -61
  135. package/docs/lib/psd/nodes/search.coffee.html +0 -23
  136. package/docs/lib/psd/path_record.coffee.html +0 -73
  137. package/docs/lib/psd/resource.coffee.html +0 -20
  138. package/docs/lib/psd/resource_section.coffee.html +0 -16
  139. package/docs/lib/psd/resources/layer_comps.coffee.html +0 -31
  140. package/docs/lib/psd/resources.coffee.html +0 -44
  141. package/docs/lib/psd/util.coffee.html +0 -24
  142. package/docs/lib/psd.coffee.html +0 -85
  143. package/index.js +0 -2
  144. package/lib/psd/blend_mode.coffee +0 -78
  145. package/lib/psd/channel_image.coffee +0 -87
  146. package/lib/psd/color.coffee +0 -10
  147. package/lib/psd/descriptor.coffee +0 -189
  148. package/lib/psd/file.coffee +0 -88
  149. package/lib/psd/header.coffee +0 -83
  150. package/lib/psd/image.coffee +0 -107
  151. package/lib/psd/image_export.coffee +0 -2
  152. package/lib/psd/image_exports/png.coffee +0 -28
  153. package/lib/psd/image_format.coffee +0 -5
  154. package/lib/psd/image_formats/layer_raw.coffee +0 -6
  155. package/lib/psd/image_formats/layer_rle.coffee +0 -7
  156. package/lib/psd/image_formats/raw.coffee +0 -3
  157. package/lib/psd/image_formats/rle.coffee +0 -38
  158. package/lib/psd/image_mode.coffee +0 -4
  159. package/lib/psd/image_modes/cmyk.coffee +0 -36
  160. package/lib/psd/image_modes/greyscale.coffee +0 -14
  161. package/lib/psd/image_modes/rgb.coffee +0 -39
  162. package/lib/psd/init.coffee +0 -21
  163. package/lib/psd/layer/blend_modes.coffee +0 -20
  164. package/lib/psd/layer/blending_ranges.coffee +0 -28
  165. package/lib/psd/layer/channel_image.coffee +0 -10
  166. package/lib/psd/layer/helpers.coffee +0 -16
  167. package/lib/psd/layer/info.coffee +0 -76
  168. package/lib/psd/layer/mask.coffee +0 -8
  169. package/lib/psd/layer/name.coffee +0 -12
  170. package/lib/psd/layer/position_channels.coffee +0 -22
  171. package/lib/psd/layer.coffee +0 -64
  172. package/lib/psd/layer_info/artboard.coffee +0 -16
  173. package/lib/psd/layer_info/blend_clipping_elements.coffee +0 -8
  174. package/lib/psd/layer_info/blend_interior_elements.coffee +0 -8
  175. package/lib/psd/layer_info/fill_opacity.coffee +0 -7
  176. package/lib/psd/layer_info/gradient_fill.coffee +0 -9
  177. package/lib/psd/layer_info/layer_id.coffee +0 -7
  178. package/lib/psd/layer_info/layer_name_source.coffee +0 -7
  179. package/lib/psd/layer_info/legacy_typetool.coffee +0 -80
  180. package/lib/psd/layer_info/locked.coffee +0 -21
  181. package/lib/psd/layer_info/metadata.coffee +0 -27
  182. package/lib/psd/layer_info/nested_section_divider.coffee +0 -22
  183. package/lib/psd/layer_info/object_effects.coffee +0 -9
  184. package/lib/psd/layer_info/section_divider.coffee +0 -38
  185. package/lib/psd/layer_info/solid_color.coffee +0 -21
  186. package/lib/psd/layer_info/typetool.coffee +0 -172
  187. package/lib/psd/layer_info/unicode_name.coffee +0 -11
  188. package/lib/psd/layer_info/vector_mask.coffee +0 -35
  189. package/lib/psd/layer_info/vector_origination.coffee +0 -9
  190. package/lib/psd/layer_info/vector_stroke.coffee +0 -9
  191. package/lib/psd/layer_info/vector_stroke_content.coffee +0 -9
  192. package/lib/psd/layer_info.coffee +0 -8
  193. package/lib/psd/layer_mask.coffee +0 -73
  194. package/lib/psd/lazy_execute.coffee +0 -86
  195. package/lib/psd/mask.coffee +0 -52
  196. package/lib/psd/node.coffee +0 -150
  197. package/lib/psd/nodes/ancestry.coffee +0 -44
  198. package/lib/psd/nodes/build_preview.coffee +0 -3
  199. package/lib/psd/nodes/group.coffee +0 -16
  200. package/lib/psd/nodes/layer.coffee +0 -14
  201. package/lib/psd/nodes/root.coffee +0 -59
  202. package/lib/psd/nodes/search.coffee +0 -20
  203. package/lib/psd/path_record.coffee +0 -72
  204. package/lib/psd/resource.coffee +0 -17
  205. package/lib/psd/resource_section.coffee +0 -16
  206. package/lib/psd/resources/guides.coffee +0 -25
  207. package/lib/psd/resources/layer_comps.coffee +0 -28
  208. package/lib/psd/resources/layer_links.coffee +0 -17
  209. package/lib/psd/resources/resolution_info.coffee +0 -26
  210. package/lib/psd/resources.coffee +0 -41
  211. package/lib/psd/util.coffee +0 -23
  212. package/lib/psd.coffee +0 -92
  213. package/output/Logo_Glyph.png +0 -0
  214. package/output/Make a change and save..png +0 -0
  215. package/output/Matte.png +0 -0
  216. package/webpack.config.js +0 -23
package/README.md CHANGED
@@ -1,189 +1,236 @@
1
1
  # PSD.js
2
2
 
3
- [![Build Status](https://travis-ci.org/meltingice/psd.js.svg?branch=master)](https://travis-ci.org/meltingice/psd.js)
4
- [![Help Contribute to Open Source](https://www.codetriage.com/meltingice/psd.js/badges/users.svg)](https://www.codetriage.com/meltingice/psd.js)
5
-
6
- A general purpose PSD parser written in Coffeescript. Based off of [PSD.rb](https://github.com/layervault/psd.rb). It allows you to work with a Photoshop document in a manageable tree structure and find out important data such as:
7
-
8
- * Document structure
9
- * Document size
10
- * Layer/folder size + positioning
11
- * Layer/folder names
12
- * Layer/folder visibility and opacity
13
- * Font data (via [psd-enginedata](https://github.com/layervault/psd-enginedata))
14
- * Text area contents
15
- * Font names, sizes, and colors
16
- * Color mode and bit-depth
17
- * Vector mask data
18
- * Flattened image data
19
- * Layer comps
20
-
21
- Runs in both NodeJS and the browser (using browserify). There are still some pieces missing that are present in PSD.rb, such as layer comp filtering, a built-in renderer, and many layer info blocks. The eventual goal is full feature parity with PSD.rb.
3
+ A general purpose Photoshop (PSD and PSB) parser for Node and the browser, written in TypeScript with no runtime dependencies. Based on [PSD.rb](https://github.com/layervault/psd.rb).
22
4
 
23
- ## Installation
5
+ It gives you a Photoshop document as a tree of groups and layers, along with:
24
6
 
25
- PSD.js has no native dependencies. Simply add `psd` to your package.json or run `npm install psd`.
7
+ * Document size, color mode and bit depth
8
+ * Layer and group names, bounds, visibility, opacity, blend modes and locks
9
+ * Text contents, fonts, sizes, colors and alignment
10
+ * Vector masks, layer styles, adjustment layers, smart objects and the rest of nearly 50 layer info blocks
11
+ * Layer comps, guides, slices, resolution info and XMP metadata
12
+ * The flattened composite image and individual layer images, as RGBA pixels or PNG
26
13
 
27
- ## Documentation
14
+ ## Installation
28
15
 
29
- **Note: work in progress**
16
+ ```sh
17
+ npm install psd
18
+ ```
30
19
 
31
- Annotated source code documentation is available [here](http://meltingice.github.io/psd.js/docs/). PROTIP: if you're wondering how to access various metadata from a layer, you'll want to see this [file](http://meltingice.github.io/psd.js/docs/lib/psd/layer/info.coffee.html).
20
+ Requires Node 20+ or a modern browser. The package is ESM only.
32
21
 
33
22
  ## Usage
34
23
 
35
- PSD.js works almost exactly the same in the browser and NodeJS.
24
+ `new PSD()` takes the file contents as an `ArrayBuffer` or any typed array (including a Node `Buffer`). It only reads the header up front; everything else is parsed lazily when you first access it, so opening large files is fast.
36
25
 
37
- ### NodeJS Example
26
+ ### Node
38
27
 
39
- ``` js
40
- var PSD = require('psd');
41
- var psd = PSD.fromFile("path/to/file.psd");
42
- psd.parse();
28
+ ```ts
29
+ import { readFile, writeFile } from 'node:fs/promises';
30
+ import { PSD } from 'psd';
43
31
 
44
- console.log(psd.tree().export());
45
- console.log(psd.tree().childrenAtPath('A/B/C')[0].export());
32
+ const psd = new PSD(await readFile('file.psd'));
46
33
 
47
- // You can also use promises syntax for opening and parsing
48
- PSD.open("path/to/file.psd").then(function (psd) {
49
- return psd.image.saveAsPng('./output.png');
50
- }).then(function () {
51
- console.log("Finished!");
52
- });
34
+ console.log(psd.width, psd.height, psd.header.modeName);
35
+ console.log(JSON.stringify(psd.tree, null, 2));
53
36
 
37
+ await writeFile('composite.png', await psd.image.toPng());
54
38
  ```
55
39
 
56
- ### Browser Example
40
+ ### Browser
57
41
 
58
- ``` js
59
- var PSD = require('psd');
42
+ ```ts
43
+ import { PSD } from 'psd';
60
44
 
61
- // Load from URL
62
- PSD.fromURL("/path/to/file.psd").then(function(psd) {
63
- document.getElementById('ImageContainer').appendChild(psd.image.toPng());
64
- });
45
+ // From a URL
46
+ const psd = new PSD(await (await fetch('/file.psd')).arrayBuffer());
65
47
 
66
- // Load from event, e.g. drag & drop
67
- function onDrop(evt) {
68
- PSD.fromEvent(evt).then(function (psd) {
69
- console.log(psd.tree().export());
70
- });
71
- }
48
+ // From a file input or drag and drop
49
+ const psd = new PSD(await file.arrayBuffer());
50
+
51
+ // Draw the composite on a canvas
52
+ const { width, height, data } = await psd.image.decode();
53
+ canvas.getContext('2d').putImageData(new ImageData(data, width, height), 0, 0);
72
54
  ```
73
55
 
74
- ### Traversing the Document
75
-
76
- To access the document as a tree structure, use `psd.tree()` to get the root node. From there, work with the tree using any of these methods:
77
-
78
- * `root()`: get the root node from anywhere in the tree
79
- * `isRoot()`: is this the root node?
80
- * `children()`: get all immediate children of the node
81
- * `hasChildren()`: does this node have any children?
82
- * `childless()`: opposite of `hasChildren()`
83
- * `ancestors()`: get all ancestors in the path of this node (excluding the root)
84
- * `siblings()`: get all sibling tree nodes including the current one (e.g. all layers in a folder)
85
- * `nextSibling()`: gets the sibling immediately following the current node
86
- * `prevSibling()`: gets the sibling immediately before the current node
87
- * `hasSiblings()`: does this node have any siblings?
88
- * `onlyChild()`: opposite of `hasSiblings()`
89
- * `descendants()`: get all descendant nodes not including the current one
90
- * `subtree()`: same as descendants but starts with the current node
91
- * `depth()`: calculate the depth of the current node (root node is 0)
92
- * `path()`: gets the path to the current node
93
-
94
- If you know the path to a group or layer within the tree, you can search by that path. Note that this always returns an Array because layer/group names do not have to be unique. The search is always scoped to the descendants of the current node, as well.
95
-
96
- ``` js
97
- psd.tree().childrenAtPath('Version A/Matte');
98
- psd.tree().childrenAtPath(['Version A', 'Matte']);
56
+ See [`examples/`](examples) for more. The Node examples run directly with `node examples/tree.ts`.
57
+
58
+ ### The document tree
59
+
60
+ `psd.tree` is the root of the document hierarchy. Every node has a `type` of `'root'`, `'group'` or `'layer'`, which TypeScript uses to narrow the node's type.
61
+
62
+ ```ts
63
+ const tree = psd.tree;
64
+
65
+ tree.children; // top-level groups and layers
66
+ tree.descendants(); // every node below, depth first
67
+ tree.subtree(); // the node itself followed by its descendants
68
+ tree.descendants().filter((n) => n.type === 'layer'); // just layers
69
+
70
+ const [matte] = tree.childrenAtPath('Version A/Matte'); // or ['Version A', 'Matte']
71
+ matte.path; // 'Version A/Matte'
72
+ matte.parent; // the 'Version A' group
73
+ matte.ancestors(); // [the 'Version A' group]
74
+ matte.siblings; // all children of the parent, including this node
75
+ matte.nextSibling;
76
+ matte.prevSibling;
77
+ matte.depth; // 2; the root is 0
78
+ matte.root; // the root node
79
+ tree.findById(32); // by layer ID
99
80
  ```
100
81
 
101
- ### Accessing Layer Data
82
+ `childrenAtPath` is case-insensitive unless you pass `{ caseSensitive: true }`, and it always returns an array because layer names don't have to be unique.
83
+
84
+ ### Node properties
85
+
86
+ Groups and layers share these properties:
87
+
88
+ ```ts
89
+ node.name;
90
+ node.id; // the layer ID
91
+ node.top; node.left; node.bottom; node.right; node.width; node.height;
92
+ node.visible; // accounts for clipping masks and layer comps
93
+ node.opacity; // 0 to 1
94
+ node.fillOpacity; // 0 to 1
95
+ node.blendMode; // 'normal', 'multiply', 'passthru', ...
96
+ node.clippingMask; // the node this one is clipped to
97
+ node.allLocked; node.positionLocked; node.compositeLocked; node.transparencyLocked;
98
+ node.colorLabel; // 'none', 'red', ...; inherited from ancestors
99
+ node.info; // layer info blocks; see below
100
+ node.layer; // the raw layer record
101
+ node.toJSON(); // a plain object; JSON.stringify(psd.tree) also works
102
+ ```
102
103
 
103
- To get data such as the name or dimensions of a layer:
104
+ Groups have `children` and `open`. Group bounds are calculated from their non-empty children. Layers have `image`. Both have `isEmpty`.
105
+
106
+ ### Layer info
107
+
108
+ Most layer data lives in "additional layer information" blocks. `node.info` (or `layer.info`) has a typed property for each block in the layer. Each block is parsed the first time you access it:
109
+
110
+ ```ts
111
+ const type = node.info.typeTool; // undefined if this isn't a text layer
112
+ if (type) {
113
+ type.text; // 'Make a change and save.'; paragraphs end in '\r', line breaks are '\u0003'
114
+ type.fonts; // ['HelveticaNeue-Light', 'AdobeInvisFont', 'MyriadPro-Regular']
115
+ type.sizes; // [33], in pixels before the transform
116
+ type.pointSizes(psd.resources.resolutionInfo.vRes); // the point sizes Photoshop shows
117
+ type.colors; // [[19, 120, 98, 255]]
118
+ type.alignment; // ['center']
119
+ type.runs; // per-run font, size, color, bold, italic...
120
+ type.transform; // { xx, xy, yx, yy, tx, ty }
121
+ type.left; type.top; type.right; type.bottom; // the text frame or paragraph box, relative to tx/ty
122
+ type.boundingBox; // { left, top, right, bottom } of the glyphs, relative to tx/ty
123
+ type.toCSS();
124
+ }
104
125
 
105
- ``` js
106
- node = psd.tree().descendants()[0];
107
- node.get('name');
108
- node.get('width');
126
+ node.info.vectorMask?.paths; // path records
127
+ node.info.solidColor; // { r, g, b }
128
+ node.info.placedLayer; // smart object descriptor
129
+ node.info.locked; // { all, position, composite, transparency }
130
+ node.info.hueSaturation; // adjustment layer settings
131
+ Object.keys(node.info); // the blocks this layer has
109
132
  ```
110
133
 
111
- PSD files also store various pieces of information in "layer info" blocks. See [this file](https://github.com/meltingice/psd.js/blob/master/lib/psd/layer/info.coffee) for all of the possible layer info blocks that PSD.js parses (in `LAYER_INFO`). Which blocks a layer has varies from layer-to-layer, but to access them you can do:
134
+ `node.layer.infoBlocks` lists every block in the layer, including ones this library doesn't parse.
112
135
 
113
- ``` js
114
- node = psd.tree().descendants()[0]
115
- node.get('typeTool').export()
116
- node.get('vectorMask').export()
136
+ Some blocks are stored as Photoshop descriptors. Their contents vary between Photoshop versions, so they're typed loosely. `descriptorColor()` converts a descriptor color (RGB, HSB, CMYK, grayscale or Lab) to `[r, g, b]`.
137
+
138
+ ### Layer styles
139
+
140
+ `node.info.objectEffects` normalizes the layer styles. Each effect is a list, since Photoshop CC allows several drop shadows, strokes and overlays per layer:
141
+
142
+ ```ts
143
+ const styles = node.info.objectEffects;
144
+ if (styles?.enabled) {
145
+ for (const shadow of styles.dropShadows) {
146
+ shadow.enabled; shadow.color; // [0, 0, 0]
147
+ shadow.opacity; shadow.blendMode; // 0.75, 'multiply'
148
+ shadow.angle; shadow.distance; shadow.size;
149
+ }
150
+ styles.strokes; // size, position, fillType, color/gradient/pattern
151
+ styles.gradientOverlays; // gradient stops, angle, style, scale
152
+ // also innerShadows, outerGlows, innerGlows, bevels, satins, colorOverlays, patternOverlays
153
+ styles.data; // the raw descriptor
154
+ }
117
155
  ```
118
156
 
119
- ### Exporting Data
157
+ Files from before Photoshop 6 store effects in `node.info.effectsLayer` instead.
158
+
159
+ ### Images
160
+
161
+ Image decoding is asynchronous because ZIP-compressed data is inflated with the platform's `DecompressionStream`.
120
162
 
121
- When working with the tree structure, you can recursively export any node to an object. This does not dump *everything*, but it does include the most commonly accessed information.
163
+ ```ts
164
+ const composite = await psd.image.decode(); // { width, height, data: RGBA Uint8ClampedArray }
165
+ const png = await psd.image.toPng(); // Uint8Array
122
166
 
123
- ``` js
124
- console.log(psd.tree().export());
167
+ if (node.type === 'layer') {
168
+ await node.image.decode(); // the layer's own pixels, at node.left/top
169
+ await node.image.decodeMask(); // the user mask as grayscale, or undefined
170
+ await node.image.toPng();
171
+ }
125
172
  ```
126
173
 
127
- Which produces something like:
128
-
129
- ``` js
130
- { children:
131
- [ { type: 'group',
132
- visible: false,
133
- opacity: 1,
134
- blendingMode: 'normal',
135
- name: 'Version D',
136
- left: 0,
137
- right: 900,
138
- top: 0,
139
- bottom: 600,
140
- height: 600,
141
- width: 900,
142
- children:
143
- [ { type: 'layer',
144
- visible: true,
145
- opacity: 1,
146
- blendingMode: 'normal',
147
- name: 'Make a change and save.',
148
- left: 275,
149
- right: 636,
150
- top: 435,
151
- bottom: 466,
152
- height: 31,
153
- width: 361,
154
- mask: {},
155
- text:
156
- { value: 'Make a change and save.',
157
- font:
158
- { name: 'HelveticaNeue-Light',
159
- sizes: [ 33 ],
160
- colors: [ [ 85, 96, 110, 255 ] ],
161
- alignment: [ 'center' ] },
162
- left: 0,
163
- top: 0,
164
- right: 0,
165
- bottom: 0,
166
- transform: { xx: 1, xy: 0, yx: 0, yy: 1, tx: 456, ty: 459 } },
167
- image: {} } ] } ],
168
- document:
169
- { width: 900,
170
- height: 600,
171
- resources:
172
- { layerComps:
173
- [ { id: 692243163, name: 'Version A', capturedInfo: 1 },
174
- { id: 725235304, name: 'Version B', capturedInfo: 1 },
175
- { id: 730932877, name: 'Version C', capturedInfo: 1 } ],
176
- guides: [],
177
- slices: [] } } }
174
+ `decode()` and `toPng()` decode the pixels again on every call and don't keep them, so exporting every layer of a large document only holds one layer's pixels at a time. Keep the result if you need it more than once.
175
+
176
+ The composite is only present if the file was saved with "Maximize Compatibility" enabled. Decoding supports RGB, CMYK, grayscale, duotone, indexed, Lab and multichannel images at 8 or 16 bits per channel, and 1-bit bitmaps, with raw, RLE or ZIP compression. CMYK, Lab and multichannel colors are converted with simple formulas rather than color profiles, so they're close to Photoshop's but not exact. Multichannel images must have 3 or 4 channels, which are treated as CMY(K) inks.
177
+
178
+ `encodePng({ width, height, data })` encodes any grayscale or RGBA pixels.
179
+
180
+ ### Resources
181
+
182
+ ```ts
183
+ psd.resources.layerComps; // [{ id, name, capturedInfo }]
184
+ psd.resources.guides; // [{ location, direction }]
185
+ psd.resources.slices; // { version, name, bounds, slices }
186
+ psd.resources.resolutionInfo; // { hRes, vRes, ... }
187
+ psd.resources.xmpMetadata; // the XMP packet as a string
188
+ psd.resources.workPath; // path records
189
+ psd.resources.savedPaths; // [{ id, name, records }]
190
+ psd.resources.bytes(1036); // the raw bytes of any resource block
178
191
  ```
179
192
 
180
- You can also export the PSD to a flattened image. Please note that, at this time, not all image modes + depths are supported.
193
+ ### Layer comps
181
194
 
182
- ``` js
183
- png = psd.image.toPng(); // get PNG object
184
- psd.image.saveAsPng('path/to/output.png').then(function () {
185
- console.log('Exported!');
186
- });
195
+ ```ts
196
+ const tree = psd.tree.filterByComp('Version A'); // a new tree with the comp's visibility and positions
197
+ node.visibleInComp('Version B');
198
+ node.positionInComp(725235304); // by name or ID
187
199
  ```
188
200
 
189
- This uses the full rasterized preview provided by Photoshop. If the file was not saved with Compatibility Mode enabled, this will return an empty image.
201
+ ## Upgrading from 3.x
202
+
203
+ 4.0 is a TypeScript rewrite with a new API. The main changes:
204
+
205
+ | 3.x | 4.0 |
206
+ | --- | --- |
207
+ | `require('psd')` | `import { PSD } from 'psd'` (ESM only) |
208
+ | `PSD.fromFile(path)` + `psd.parse()` | `new PSD(await readFile(path))`; no `parse()` |
209
+ | `PSD.open(path)` | `new PSD(await readFile(path))` |
210
+ | `PSD.fromURL(url)` / `fromEvent` / `fromDroppedFile` | `new PSD(await response.arrayBuffer())` / `new PSD(await file.arrayBuffer())` |
211
+ | `psd.tree()` | `psd.tree` |
212
+ | `node.get('name')`, `node.get('width')` | `node.name`, `node.width` |
213
+ | `node.get('typeTool')`, `layer.typeTool()` | `node.info.typeTool` |
214
+ | `typeTool.export().value`, `typeTool.fonts()` | `typeTool.text`, `typeTool.fonts` |
215
+ | `typeTool.lengthArray()`, `fontStyles()`, `fontWeights()`, `textDecoration()` | `typeTool.runs` |
216
+ | `node.export()` | `node.toJSON()` |
217
+ | `node.isLayer()`, `isGroup()`, `isRoot()` | `node.type === 'layer'`, etc. |
218
+ | `node.children()`, `siblings()`, `depth()`, `path()` ... | properties: `node.children`, `node.siblings`, `node.depth`, `node.path` |
219
+ | `node.hasChildren()`, `childless()`, `hasSiblings()`, `onlyChild()` | `node.children.length`, `node.siblings.length` |
220
+ | `psd.image.pixelData` | `(await psd.image.decode()).data` |
221
+ | `psd.image.toPng()` (pngjs / `<img>`) | `await psd.image.toPng()` returns PNG bytes |
222
+ | `psd.image.saveAsPng(path)` | `writeFile(path, await psd.image.toPng())` |
223
+ | `psd.resources.resource('layerComps').export()` | `psd.resources.layerComps` |
224
+ | `psd.layers` | `psd.layers` (now also populated for 16-bit files) |
225
+
226
+ New in 4.0: PSB support, 16-bit layers, ZIP-compressed image data, bitmap/indexed/Lab/multichannel decoding, typed layer styles, ~30 more layer info blocks, slices, paths, XMP, lock inheritance, layer comp filtering, and fixes for grayscale layer images.
227
+
228
+ ## Limitations
229
+
230
+ * There's no renderer, so layers can't be composited, and a node can't be exported with its effects applied. The composite stored in the file is available as `psd.image`.
231
+ * 32-bit images can be parsed but not decoded to pixels.
232
+ * Descriptors containing object arrays (`ObAr`), which are undocumented, throw when parsed.
233
+
234
+ ## License
235
+
236
+ MIT
@@ -0,0 +1,20 @@
1
+ import type { Reader } from './reader.ts';
2
+ /**
3
+ * Descriptors are Photoshop's self-describing key/value structures (the "Action Descriptor"
4
+ * format). Their contents vary by block and Photoshop version, so values are typed loosely.
5
+ */
6
+ export interface Descriptor {
7
+ class: DescriptorClass;
8
+ [key: string]: any;
9
+ }
10
+ export interface DescriptorClass {
11
+ name: string;
12
+ id: string;
13
+ }
14
+ export interface UnitValue {
15
+ id: string;
16
+ unit: string | undefined;
17
+ value: number;
18
+ }
19
+ export declare function readDescriptor(r: Reader): Descriptor;
20
+ //# sourceMappingURL=descriptor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"descriptor.d.ts","sourceRoot":"","sources":["../src/descriptor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE1C;;;GAGG;AACH,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,eAAe,CAAC;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;CACf;AAaD,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,GAAG,UAAU,CAQpD"}
@@ -0,0 +1,114 @@
1
+ const UNITS = {
2
+ '#Ang': 'Angle',
3
+ '#Rsl': 'Density',
4
+ '#Rlt': 'Distance',
5
+ '#Nne': 'None',
6
+ '#Prc': 'Percent',
7
+ '#Pxl': 'Pixels',
8
+ '#Mlm': 'Millimeters',
9
+ '#Pnt': 'Points',
10
+ };
11
+ export function readDescriptor(r) {
12
+ const data = { class: readClass(r) };
13
+ const count = r.int32();
14
+ for (let i = 0; i < count; i++) {
15
+ const key = readId(r);
16
+ data[key] = readItem(r, r.ascii(4));
17
+ }
18
+ return data;
19
+ }
20
+ function readClass(r) {
21
+ return { name: r.unicode(), id: readId(r) };
22
+ }
23
+ function readId(r) {
24
+ const len = r.int32();
25
+ return r.ascii(len === 0 ? 4 : len);
26
+ }
27
+ function readItem(r, type) {
28
+ switch (type) {
29
+ case 'bool':
30
+ return r.bool();
31
+ case 'type':
32
+ case 'GlbC':
33
+ return readClass(r);
34
+ case 'Objc':
35
+ case 'GlbO':
36
+ return readDescriptor(r);
37
+ case 'doub':
38
+ return r.float64();
39
+ case 'enum':
40
+ return { type: readId(r), value: readId(r) };
41
+ case 'alis':
42
+ return r.ascii(r.int32());
43
+ case 'Pth ': {
44
+ r.skip(4); // length
45
+ const sig = r.ascii(4);
46
+ r.skip(4); // path size, little endian
47
+ const chars = r.view.getInt32(r.pos, true);
48
+ r.skip(4);
49
+ return { sig, path: r.unicode(chars) };
50
+ }
51
+ case 'long':
52
+ return r.int32();
53
+ case 'comp':
54
+ return r.int64();
55
+ case 'VlLs': {
56
+ const count = r.int32();
57
+ return Array.from({ length: count }, () => readItem(r, r.ascii(4)));
58
+ }
59
+ case 'tdta':
60
+ return r.bytesView(r.int32());
61
+ case 'obj ':
62
+ return readReference(r);
63
+ case 'TEXT':
64
+ return r.unicode();
65
+ case 'UntF':
66
+ return readUnit(r, () => r.float64());
67
+ case 'UnFl': {
68
+ // A unit followed by a list of doubles. Only seen inside object arrays.
69
+ const id = r.ascii(4);
70
+ const count = r.int32();
71
+ return { id, unit: UNITS[id], values: Array.from({ length: count }, () => r.float64()) };
72
+ }
73
+ default:
74
+ // Includes 'ObAr' (object array), which is undocumented. Unknown types would desync the
75
+ // reader, so fail loudly instead of returning garbage.
76
+ throw new Error(`Unsupported descriptor item type '${type}' at offset ${r.pos - 4}`);
77
+ }
78
+ }
79
+ function readUnit(r, read) {
80
+ const id = r.ascii(4);
81
+ return { id, unit: UNITS[id], value: read() };
82
+ }
83
+ function readReference(r) {
84
+ const count = r.int32();
85
+ const items = [];
86
+ for (let i = 0; i < count; i++) {
87
+ const type = r.ascii(4);
88
+ let value;
89
+ switch (type) {
90
+ case 'prop':
91
+ value = { class: readClass(r), id: readId(r) };
92
+ break;
93
+ case 'Clss':
94
+ value = readClass(r);
95
+ break;
96
+ case 'Enmr':
97
+ value = { class: readClass(r), type: readId(r), value: readId(r) };
98
+ break;
99
+ case 'Idnt':
100
+ case 'indx':
101
+ case 'rele':
102
+ value = r.int32();
103
+ break;
104
+ case 'name':
105
+ value = r.unicode();
106
+ break;
107
+ default:
108
+ throw new Error(`Unsupported descriptor reference type '${type}' at offset ${r.pos - 4}`);
109
+ }
110
+ items.push({ type, value });
111
+ }
112
+ return items;
113
+ }
114
+ //# sourceMappingURL=descriptor.js.map
@@ -0,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/List [ 1 .5 true ] /Dict << /Name /Value >> >>`.
4
+ * Strings are byte strings with `\` escapes, and are UTF-16BE when they start with a BOM.
5
+ */
6
+ export type EngineValue = string | number | boolean | EngineValue[] | EngineDict;
7
+ export interface EngineDict {
8
+ [key: string]: any;
9
+ }
10
+ export declare function parseEngineData(bytes: Uint8Array): EngineDict;
11
+ //# sourceMappingURL=engine-data.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-data.d.ts","sourceRoot":"","sources":["../src/engine-data.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,WAAW,EAAE,GAAG,UAAU,CAAC;AACjF,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAMD,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAAU,GAAG,UAAU,CAuE7D"}
@@ -0,0 +1,82 @@
1
+ const utf16 = new TextDecoder('utf-16be');
2
+ const isSpace = (b) => b === 0x20 || b === 0x09 || b === 0x0a || b === 0x0d || b === 0x00;
3
+ const isDelimiter = (b) => isSpace(b) || b === 0x2f || b === 0x5b || b === 0x5d || b === 0x3c || b === 0x3e || b === 0x28;
4
+ export function parseEngineData(bytes) {
5
+ let pos = 0;
6
+ const skipSpace = () => {
7
+ while (pos < bytes.length && isSpace(bytes[pos]))
8
+ pos++;
9
+ };
10
+ const word = () => {
11
+ const start = pos;
12
+ while (pos < bytes.length && !isDelimiter(bytes[pos]))
13
+ pos++;
14
+ return String.fromCharCode(...bytes.subarray(start, pos));
15
+ };
16
+ const string = () => {
17
+ pos++; // (
18
+ const out = [];
19
+ for (;;) {
20
+ if (pos >= bytes.length)
21
+ throw new Error('Unterminated EngineData string');
22
+ const b = bytes[pos++];
23
+ if (b === 0x29)
24
+ break; // )
25
+ out.push(b === 0x5c ? bytes[pos++] : b); // \ escapes the next byte
26
+ }
27
+ if (out[0] === 0xfe && out[1] === 0xff)
28
+ return utf16.decode(new Uint8Array(out.slice(2)));
29
+ return String.fromCharCode(...out);
30
+ };
31
+ const value = () => {
32
+ skipSpace();
33
+ const b = bytes[pos];
34
+ if (b === 0x3c && bytes[pos + 1] === 0x3c) {
35
+ pos += 2;
36
+ const dict = {};
37
+ for (;;) {
38
+ skipSpace();
39
+ if (bytes[pos] === 0x3e && bytes[pos + 1] === 0x3e) {
40
+ pos += 2;
41
+ return dict;
42
+ }
43
+ if (bytes[pos] !== 0x2f)
44
+ throw new Error(`Expected EngineData key at offset ${pos}`);
45
+ pos++;
46
+ dict[word()] = value();
47
+ }
48
+ }
49
+ if (b === 0x5b) {
50
+ pos++;
51
+ const list = [];
52
+ for (;;) {
53
+ skipSpace();
54
+ if (bytes[pos] === 0x5d) {
55
+ pos++;
56
+ return list;
57
+ }
58
+ list.push(value());
59
+ }
60
+ }
61
+ if (b === 0x28)
62
+ return string();
63
+ if (b === 0x2f) {
64
+ pos++;
65
+ return word();
66
+ }
67
+ const token = word();
68
+ if (token === 'true')
69
+ return true;
70
+ if (token === 'false')
71
+ return false;
72
+ const n = Number(token);
73
+ if (token === '' || Number.isNaN(n))
74
+ throw new Error(`Unexpected EngineData token '${token}' at offset ${pos}`);
75
+ return n;
76
+ };
77
+ const root = value();
78
+ if (typeof root !== 'object' || Array.isArray(root))
79
+ throw new Error('EngineData root is not a dictionary');
80
+ return root;
81
+ }
82
+ //# sourceMappingURL=engine-data.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-data.js","sourceRoot":"","sources":["../src/engine-data.ts"],"names":[],"mappings":"AAUA,MAAM,KAAK,GAAG,IAAI,WAAW,CAAC,UAAU,CAAC,CAAC;AAC1C,MAAM,OAAO,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI,CAA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