### Example: Recording an Alert Action
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/action-recording
This example demonstrates recording an Action step that displays an alert message. It shows how to define the handler function and call `recordAction` with the necessary parameters.
```javascript
// Start recording an Action, then execute the code below.
async function alertHandler(context, dataObj) {
require('photoshop').core.showAlert(dataObj.message);
return dataObj;
};
require('photoshop').action.recordAction(
{
"name": "Hello Alert",
"methodName": "alertHandler"
},
{message: "Hello!"}
);
// Stop recording, and play the Action.
```
--------------------------------
### Guide Object Reference
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/guide
This section details the properties and methods available for the Guide object.
```APIDOC
## Guide Object
Represents a single guide in the document.
### Properties
* **coordinate** (_number_) - Read Write - Available from version 23.0. Position of the guide measured from the ruler origin in pixels. The value can be a decimal. Note: the user can move the ruler origin which will affect the position value of the guides. Fixes in Photoshop 24.0: Return correct value when resolution is not 72 PPI.
* **direction** (_Direction_) - Read Write - Available from version 23.0. Indicates whether the guide is vertical or horizontal.
* **docId** (_number_) - Read - Available from version 23.0. The ID of the document of this guide.
* **id** (_number_) - Read - Available from version 23.0. For use with batchPlay operations. This guide ID, along with its document ID can be used to represent this guide for the lifetime of this document or the guide.
* **parent** (_Document_) - Read - Available from version 23.0. Owner document of this guide.
* **typename** (_string_) - Read - Available from version 23.0. The class name of the referenced object: "Guide".
### Methods
* **delete** - Available from version 23.0. Returns void. Deletes the guide from the document.
```
--------------------------------
### Filter Plugin Entry Point
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/cpp-pluginsdk
Example of how to extract the basic suite and plugin reference from the `PluginMain` entry point for Filter plugins.
```c
DLLExport MACPASCAL void PluginMain(const int16 selector,
FilterRecordPtr filterRecord,
intptr_t * data,
int16 * result) {
sSPBasic = filterRecord->sSPBasic;
gPlugInRef = filterRecord->plugInRef;
...
```
--------------------------------
### Sample Output from Color Sampler
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
Example of the expected output format when using the colorSampler command with batchPlay.
```json
[{
colorSampler: {
_obj: "CMYKColorClass",
black: 0,
cyan: 26.27,
magenta: 4.71,
yellowColor: 0
},
sampledData: true
}]
```
--------------------------------
### Automation Plugin Entry Point
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/cpp-pluginsdk
Example of how to extract the plugin reference and basic suite from the `AutoPluginMain` entry point for Automation plugins.
```c
DLLExport SPAPI SPErr AutoPluginMain(const char* caller, const char* selector, void* message) {
SPMessageData* basicMessage = (SPMessageData*) message;
sSPBasic = basicMessage->basic;
gPlugInRef = basicMessage->self;
...
```
--------------------------------
### UXP Messaging Listener Setup
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/cpp-pluginsdk
Shows how to add and remove a listener in a UXP plugin to receive messages from C++ SDK plugins.
```javascript
let callback = (o) => {
console.log("Message from " + o.pluginId + ":" + o.message);
}
require('photoshop').messaging.addSDKMessagingListener(callback);
...
// You can remove your listener using this API
require('photoshop').messaging.removeSDKMessagingListener(callback);
```
--------------------------------
### Remove All Guides
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/guides
Clears all guides from the active document's collection. This action is irreversible.
```javascript
app.activeDocument.guides.removeAll();
```
--------------------------------
### Add a Horizontal Guide
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/guides
Adds a new horizontal guide to the active document at a specified pixel coordinate. Ensure the UXP API is available.
```javascript
app.activeDocument.guides.add(Constants.Direction.HORIZONTAL, 20);
```
--------------------------------
### Add a Vertical Guide
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/guides
Adds a new vertical guide to the active document at a specified pixel coordinate. Ensure the UXP API is available.
```javascript
app.activeDocument.guides.add(Constants.Direction.VERTICAL, 50);
```
--------------------------------
### Windows Display Configuration Example
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/displayunits
Output from `getDisplayConfiguration` on a Windows machine with a 27" 4k display and scale factor set to 2. This shows pixel values for bounds and physical resolution.
```json
{
"globalBounds": {
"bottom": 2160,
"left": 0,
"right": 3840,
"top": 0
},
"physicalResolution": {
"horizontal": 163,
"vertical": 163
},
"scaleFactor": 2
}
```
--------------------------------
### Get Font by Name
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/textfont
Retrieves a TextFont object by its name. Ensure the font is installed on the system.
```javascript
const arialMTFont = require('photoshop').app.fonts.getByName("ArialMT");
```
--------------------------------
### Guides Collection
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/guides
The Guides collection allows for array-like access to a document's guides. You can add new guides, access existing ones by index, and remove all guides.
```APIDOC
## Guides Collection
### Description
A collection class allowing for array access into a document's guides. Access this collection through `Document.guides` property.
### Properties
* **length** (_number_): Number of Guide elements in this collection. (R, 23.0)
* **parent** (_Document_): The owner document of this Guide collection. (R, 23.0)
### Methods
#### add
Adds a guide for the collection at the given coordinate and direction.
**Fixes in Photoshop 24.0:**
* Correct coordinate when resolution is not 72 PPI
* Returns valid instance of guide
##### Parameters
* **direction** (_Direction_): Indicates whether the guide is vertical or horizontal.
* **coordinate** (_number_): Position of the guide measured from the ruler origin in pixels. The value can be a decimal. Note: the user can move the ruler origin which will affect the position value of the guides. (23.0)
#### removeAll
Clears all guides from this collection. (23.0)
### Example Usage
```javascript
// Adds a new horizontal guide at 20 pixels from the ruler origin
app.activeDocument.guides.add(Constants.Direction.HORIZONTAL, 20);
```
### Indexing
* **index** (_number_): Used to access the guides in the collection. (e.g., `app.activeDocument.guides[0]`)
```
--------------------------------
### Execute BatchPlay Commands
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopaction
Perform batchPlay commands, similar to ExtendScript's executeAction. This example hides the target layer.
```javascript
const target = { _ref: 'layer', _enum: 'ordinal', _value: 'targetEnum' };
const commands = [{ _obj: 'hide', _target: target }];
await action.batchPlay(commands);
```
--------------------------------
### Accessing Photoshop Documents
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/document
Demonstrates how to get references to the currently active document, a specific open document by index, and how to open a document from a UXP File entry.
```javascript
const {app, constants} = require('photoshop');
// The currently active document from the Photoshop object
const currentDocument = app.activeDocument;
// Choose one of the open documents from the Photoshop object
const secondDocument = app.documents[1];
// You can also create an instance of a document via a UXP File entry
let fileEntry = require('uxp').storage.localFileSystem.getFileForOpening();
const newDocument = await app.open('/project.psd');
```
--------------------------------
### Get All Document Properties with batchPlay
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
When the 'get' command is used without a target property, it returns all possible properties for the target. This is primarily for development to discover supported properties.
```javascript
var target = {_ref: [
{_ref: "document", _id: someDocumentID},
{_ref: "application"}
]};
var command = {_obj: "get", _target: target};
let result = await photoshop.action.batchPlay([command], {});
```
--------------------------------
### Create Thumbnail with getPixels
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/imaging
This example demonstrates how to create a thumbnail by requesting pixel data with a specified target height. The getPixels function can scale the image data to fit the target size, potentially using cached pyramid levels for performance.
```javascript
const thumbnail = await imaging.getPixels({
targetSize: {
height: 100
}
});
```
--------------------------------
### Create RGBA ImageData from Buffer
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/imaging
Example demonstrating how to create RGBA image data from a Uint8Array buffer. The 'options' object specifies image dimensions, components, color profile, and color space.
```javascript
const width = 30;
const height = 40;
const components = 4; // RGBA
const componentCount = width * height;
const dataSize = componentCount * components;
const arrayBuffer = new Uint8Array(dataSize);
// Add some (chunky) data to the buffer
for (let i = 0 ; i < componentCount; i += components) {
arrayBuffer[index] = 255; // red
arrayBuffer[index+1] = 0; // green
arrayBuffer[index+2] = 0; // blue
arrayBuffer[index+3] = 127; // alpha
}
const options = {
width: width,
height: height,
components: components,
colorProfile: "sRGB IEC61966-2.1",
colorSpace: "RGB"
};
const imageData = await imaging.createImageDataFromBuffer(arrayBuffer, options)
```
--------------------------------
### getColorProfiles
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/photoshop
Retrieves a list of installed color profiles for a specified color mode (RGB or Gray).
```APIDOC
## getColorProfiles
### Description
List of installed color profiles, for RGB and Gray modes.
### Method
GET (implied by getColorProfiles)
### Endpoint
/
### Parameters
#### Path Parameters
None
#### Query Parameters
- **colorMode** (string) - Optional - Specify which color mode's profiles to list. Defaults to "RGB". Options: "Gray".
```
--------------------------------
### Demonstrate Color Model Conversion
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/solidcolor
This example shows how interacting with a SolidColor object can change its internal color model representation. Photoshop automatically converts colors based on 'Edit > Color Settings'.
```javascript
const SolidColor = require("photoshop").app.SolidColor;
const c = new SolidColor();
console.log(c.base.typename); // By default, this will be "RGBColor"
c.cmyk.cyan = 50; // Photoshop will convert the color to CMYK using Edit > Color Settings data
console.log(c.base.typename); // Now, the typename will be "CMYKColor"
c.rgb.green = 128; // Typename will change back to "RGBColor"
```
--------------------------------
### Define and Use CalculationsOptions
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/objects/options/calculationsoptions
Construct an object literal with CalculationsOptions properties and pass it to Document.calculations. This example demonstrates setting up two sources, a blend mode, opacity, and the desired result channel.
```javascript
const options = {
source1: {
document: doc,
layer: doc.layers[0],
channel: CalculationsChannel.GRAY,
invert: true
},
source2: {
document: doc,
layer: CalculationsLayer.MERGED,
channel: doc.channels[2]
},
blending: CalculationsBlendMode.DARKEN,
opacity: 50,
result: CalculationsResult.NEWCHANNEL
};
await require('photoshop').app.activeDocument.calculations(options);
```
--------------------------------
### Action Reference by Name
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
An example of an action reference using the name form to specify a document. This targets a document by its string name.
```json
{_ref: "document", _name: "Untitled-1"}
```
--------------------------------
### Basic executeAsModal with a loop
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/executeasmodal
This example demonstrates a basic `executeAsModal` call with a target function that contains a `while` loop. The operation continues until the user manually cancels it. Photoshop APIs like `batchPlay` will raise an exception on subsequent calls after cancellation.
```javascript
async function targetFunction(executionContext, descriptor) {
let target = {
_ref: [
{_ref: "property", _property: "hostName"},
{_ref: "application", _enum: "ordinal", _value: "targetEnum"}
]
};
let command = {_obj: "get", _target: target};
while (true) { // <-- WAIT FOR THE USER TO MANUALLY CANCEL
await psAction.batchPlay([command], {});
}
}
await require("photoshop").core.executeAsModal(
targetFunction,
{commandName: "User Cancel Test"}
);
```
--------------------------------
### Import and Use Constants
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/modules/constants
Import the constants object from the photoshop module to use various constants in your UXP scripts. This example shows how to resize an image using a specified interpolation method.
```javascript
const {app, constants} = require("photoshop");
await app.activeDocument.resizeImage(
800, 600, 100,
constants.InterpolationMethod.AUTOMATIC
);
```
--------------------------------
### Font Size with Document Resolution
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/textitem
Example of setting font size, noting that valid ranges can depend on document resolution (e.g., 72ppi).
```javascript
// Range: 0.01..1296—for a 72ppi document
textItem.characterStyle.size = 1000;
```
--------------------------------
### Creating a Straight Line Path
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/pathpointinfo
This script demonstrates how to create a straight line path using PathPointInfo objects. It defines start and stop points with identical coordinates for a straight segment and adds it to the document.
```javascript
function drawLine(doc: Document, start: number[], stop: number[]) {
const startPoint = new PathPointInfo();
startPoint.anchor = start;
startPoint.leftDirection = start;
startPoint.rightDirection = start;
startPoint.kind = Constants.PointKind.CORNERPOINT;
const stopPoint = new PathPointInfo();
stopPoint.anchor = stop;
stopPoint.leftDirection = stop;
stopPoint.rightDirection = stop;
stopPoint.kind = Constants.PointKind.CORNERPOINT;
const spi = new SubPathInfo();
spi.closed = false;
spi.operation = Constants.ShapeOperation.SHAPEXOR;
spi.entireSubPath = [startPoint, stopPoint];
const line = doc.pathItems.add("Line", [spi]);
line.strokePath(Constants.ToolType.PENCIL);
line.remove();
}
drawLine(app.activeDocument, [100,100], [200,200]);
```
--------------------------------
### Action Descriptor for Sampling a Pixel
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
An example of an action descriptor to sample the color of a pixel at specific coordinates within the active document.
```javascript
{
_obj: "colorSampler",
_target: {_ref: "document", _enum: "ordinal", _value: "targetEnum"},
samplePoint: {
horizontal: 100,
vertical: 100
}
}
```
--------------------------------
### Open Document with File Entry
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/photoshop
Opens a specified document using a UXPFileEntry object. This requires obtaining the file entry first, for example, using `getFileForOpening()`.
```javascript
let entry = await require('uxp').storage.localFileSystem.getFileForOpening()
const document = await app.open(entry);
```
--------------------------------
### Create Grayscale ImageData for Masks
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/imaging
Example for creating grayscale image data for layer masks or document selections. Use `components: 1`, `colorSpace: "Grayscale"`, and `colorProfile: "Gray Gamma 2.2"`.
```javascript
const width = 30;
const height = 40;
const componentCount = width * height;
const arrayBuffer = new Uint8Array(componentCount);
for (let i = 0 ; i < componentCount; ++i) {
arrayBuffer[i] = 127; // all set to the median value
}
const options = {
width: width,
height: height,
components: 1, // masks are grayscale
chunky: false,
colorProfile: "Gray Gamma 2.2",
colorSpace: "Grayscale"
};
const maskData = await imaging.createImageDataFromBuffer(arrayBuffer, options)
```
--------------------------------
### Get Plugin Information
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Retrieves information about the plugin's execution, such as pending tasks and batch play counts. Intended for plugin development and debugging.
```javascript
await core.getPluginInfo();
```
--------------------------------
### Get GPU Information
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Returns OpenGL and OpenCL information for the available graphics processor. The output includes details like version, memory, and name for both OpenGL and OpenCL.
```javascript
const { gpuInfoList, clgpuInfoList } = core.getGPUInfo();
console.log(JSON.stringify(gpuInfoList));
// > [{"version":"2.1 ATI-4.5.14","memoryMB":8192,"name":"16915464", ...}]
console.log(JSON.stringify(clgpuInfoList));
// > [{"version":"OpenCL 1.2 ","memoryMB":8589,"name":"AMD Radeon Pro 580X Compute Engine", ...}]
```
--------------------------------
### Action Reference by Index
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
An example of an action reference using the index form to specify a document. Note that indices are 1-based and can change if elements are added or removed.
```json
{_ref: "document", _index: 1}
```
--------------------------------
### Get CPU Information
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Fetches information about the host CPU, including logical cores, frequency, and vendor. Useful for determining CPU type (AMD, ARM).
```javascript
const { logicalCores, frequencyMhz, vendor } = core.getCPUInfo();
const isAMD = vendor === 'AMD';
const isARM = vendor === 'ARM';
```
--------------------------------
### Encode ImageData to Base64 JPEG and Display
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/imaging
Example of encoding image data to a base64 JPEG string and setting it as the `src` for an `
` element. This is useful for displaying images created within UXP.
```javascript
const imageElement = document.createElement('img');
const jpegData = await imaging.encodeImageData({"imageData": imgObj.imageData, "base64": true});
const dataUrl = "data:image/jpeg;base64," + jpegData;
imageElement.src = dataUrl;
document.body.appendChild(imageElement);
```
--------------------------------
### Get Display Configuration
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Retrieves the current display configuration for all connected displays. The units for resolution may differ between platforms (logical points on Mac, pixels on Windows).
```javascript
core.getDisplayConfiguration({ physicalResolution: true });
```
--------------------------------
### Acquiring Suites and Sending UXP Message
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/cpp-pluginsdk
Demonstrates acquiring the necessary suites (PIUXPSuite and ActionDescriptor) and sending a message to a UXP plugin.
```c
// in your main method
sSPBasic->AcquireSuite(kPSUXPSuite,
kPSUXPSuiteVersion1,
(const void**)&sUxpProcs);
sSPBasic->AcquireSuite(kPSActionDescriptorSuite,
kPSActionDescriptorSuiteVersion,
(const void**)&sDescriptorProcs);
PIActionDescriptor desc;
sDescriptorProcs->Make(&desc);
sDescriptorProcs->PutString(desc, 'helo', "Hello World!");
sDescriptorProcs->PutFloat(desc, 'fltp', 0.952);
const char* UXP_MANIFEST_ID = "com.your.pluginId";
sUxpProcs->SendUXPMessage(gPlugInRef, UXP_MANIFEST_ID, desc);
}
```
--------------------------------
### Create a Layer Comp with Options
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/objects/createoptions/layercompcreateoptions
Demonstrates how to create a new layer comp with specified options such as name, comment, and visibility. This is useful for programmatically managing layer comps with custom settings.
```javascript
const options = { name: "mockup", comment: "First attempt", visibility: true };
await require('photoshop').app.activeDocument.layerComps.add(options);
```
--------------------------------
### Get Document Title with batchPlay
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
Use the 'get' action command with a target property to retrieve the title of a specific document. This is a common use case for identifying open documents.
```javascript
var target = {_ref: [
{_property: "title"},
{_ref: "document", _id: someDocumentID},
{_ref: "application"}
]};
var command = {_obj: "get", _target: target};
let result = await photoshop.action.batchPlay([command], {});
```
--------------------------------
### Create a Layer Group with Options
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/objects/createoptions/grouplayercreateoptions
Demonstrates how to create a new layer group with a specified name and opacity using the `createLayerGroup` method.
```javascript
const options = { name: "myGroup", opacity: 50 };
await require('photoshop').app.activeDocument.createLayerGroup(options);
```
--------------------------------
### Create a Pixel Layer with Options
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/objects/createoptions/pixellayercreateoptions
Demonstrates how to create a new pixel layer with a specified name, opacity, and blend mode using the `createLayer` method. Ensure the `photoshop` module and `constants` are available.
```javascript
const options = { name: "myLayer", opacity: 80, blendMode: constants.BlendMode.COLORDODGE };
await require('photoshop').app.activeDocument.createLayer(options);
```
--------------------------------
### Direction
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/modules/constants
Represents orientation, used for guides.
```APIDOC
## Direction
### Description
Used in multiple places to represent orientation. Orientation of a guide in Guide.direction.
### Enum Values
- **HORIZONTAL**
- **VERTICAL**
```
--------------------------------
### Get All Open Documents
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference
Retrieve an array of all currently open documents in Photoshop.
```javascript
const allDocuments = app.documents;
```
--------------------------------
### Get Active Document
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference
Retrieve the currently active document from the Photoshop application.
```javascript
const doc = app.activeDocument;
```
--------------------------------
### Create Document with ExecuteAsModal
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference
Demonstrates creating a new document using a predefined preset. All document modification commands must be wrapped in executeAsModal.
```javascript
async function makeDefaultDocument(executionContext) {
const app = require('photoshop').app;
let myDoc = await app.createDocument({preset: "My Web Preset 1"});
}
await require('photoshop').core.executeAsModal(makeDefaultDocument);
```
--------------------------------
### Get Document Dimensions and Resolution
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference
Retrieve the width, height, and resolution of the active document. This operation is synchronous.
```javascript
const app = require('photoshop').app;
const myDoc = app.activeDocument;
const height = myDoc.height;
const width = myDoc.width;
const resolution = myDoc.resolution;
console.log(`Doc size is ${width} x ${height}. Resolution is ${resolution}`);
```
--------------------------------
### Create a Text Layer with Options
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/document
Creates a text layer with options for name, content, and font size.
```javascript
await doc.createTextLayer()
await doc.createTextLayer({
name: "myTextLayer",
contents: "Hello, World!",
fontSize: 32
});
```
--------------------------------
### Get User Idle Time
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Returns the current user idle time in seconds. Can be used in conjunction with setUserIdleTime.
```javascript
await core.getUserIdleTime();
```
--------------------------------
### Get Menu Command State
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Checks if a specific menu command is available for invocation. Requires the commandID to be specified.
```javascript
// can a Fill be performed?
const canFill = await core.getMenuCommandState({ commandID: 1042 });
```
--------------------------------
### Iterate Through Documents
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/changelog
Use the new collection classes to iterate through all open documents. This example logs the title of each document.
```javascript
app.documents.forEach(h => console.log(h.title));
```
--------------------------------
### Add Color Sampler and Check Length
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/colorsamplers
Demonstrates adding a color sampler and immediately checking the updated length of the collection. Confirms the addition was successful.
```javascript
app.activeDocument.colorSamplers.add({x: 20, y: 20});
app.activeDocument.colorSamplers.length; // returns 1
```
--------------------------------
### Sample Color from Document
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/document
Samples a SolidColor object from a specified position in the document. Requires the 'app' object to be available.
```javascript
let col = await app.activeDocument.sampleColor({x: 100, y: 100});
console.log(col.rgb);
// {
// red: 233,
// green: 179,
// blue: 135,
// hexValue: "E9B387"
// }
```
--------------------------------
### Action Reference to a Property
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
An example of an action reference targeting a specific property of an object, in this case, the 'title' property.
```json
{_property: "title"}
```
--------------------------------
### PhotoshopImageData getData Example
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/imaging
Retrieves pixel data from a PhotoshopImageData instance. The returned data is a typed array, and the method is asynchronous.
```javascript
const pixelData = await imageObj.imageData.getData()
```
--------------------------------
### Create a Pixel Layer with Options
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/document
Creates a pixel layer with specific options, including name, opacity, and fillNeutral.
```javascript
await doc.createPixelLayer({
name: "myLayer",
opacity: 80,
fillNeutral: true
});
```
--------------------------------
### Action Descriptor for Hiding a Layer
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
An example of an action descriptor in actionJSON format to hide the active layer in the frontmost document.
```javascript
{
_obj: "hide",
_target: [
{_ref: "layer", _enum: "ordinal", _value: "targetEnum"},
{_ref: "document", _enum: "ordinal", _value: "targetEnum"}
]
}
```
--------------------------------
### Create a New Document with Options
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/objects/createoptions/documentcreateoptions
Construct an object literal with DocumentCreateOptions properties and pass it to Photoshop.app.createDocument to create a new document.
```javascript
const options = { name: "Web mockup", preset: "Web Large" };
require('photoshop').app.createDocument(options);
```
--------------------------------
### Accessing the Imaging API
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/imaging
Import the imaging sub-module from the Photoshop API to begin using its functionalities.
```javascript
const imaging = require("photoshop").imaging;
```
--------------------------------
### Get Layer Tree (Sync)
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Synchronously retrieves the full hierarchy of layers in a document, represented as nested lists. Requires the documentID.
```javascript
core.getLayerTreeSync({ documentID: 123 });
```
--------------------------------
### Get Layer Tree (Async)
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Asynchronously retrieves the full hierarchy of layers in a document, represented as nested lists. Requires the documentID.
```javascript
await core.getLayerTree({ documentID: 123 });
```
--------------------------------
### Create New Document with Custom Options
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/documents
Creates a new document with specified dimensions, resolution, color mode, and fill. This allows for precise control over the new document's properties.
```javascript
let newDoc2 = await app.documents.add({
width: 800,
height: 600,
resolution: 300,
mode: "RGBColorMode",
fill: "transparent"
});
```
--------------------------------
### Execute a 'Make Layer' Action
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
This snippet demonstrates how to execute a single Photoshop action descriptor to create a new layer. It uses `batchPlay` to send the command and `executeAsModal` to ensure proper execution context.
```javascript
async function actionCommands() {
let command;
let result;
let psAction = action;
// Make layer
command = {_obj: "make", _target: [{_ref: "layer"}], layerID: 2};
result = await psAction.batchPlay([command], {});
}
async function runModalFunction() {
await core.executeAsModal(actionCommands, {commandName: "Action Commands"});
}
await runModalFunction();
```
--------------------------------
### Create New Document Using a Preset
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/documents
Creates a new document based on a predefined Photoshop preset. This is useful for quickly setting up documents with specific dimensions and settings.
```javascript
let newDoc3 = await app.documents.add({preset: "My Default Size 1"});
```
--------------------------------
### Action Methods
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/action
Provides documentation for the methods available on the Action class, including delete, duplicate, and play.
```APIDOC
## delete
### Description
Deletes this Action from the Actions panel.
### Method
void
### Parameters
None
### Response
None
## duplicate
### Description
Creates a copy of this Action, placing it in the same Action Set.
### Method
Action
### Parameters
None
### Response
- **Action** (Action): A copy of the Action.
## play
### Description
Plays this Action.
### Method
async : Promise
### Parameters
None
### Response
- **Promise** (Promise): A promise that resolves when the action has finished playing.
```
--------------------------------
### Import SolidColor Class
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/solidcolor
Import the SolidColor class from Photoshop's app object to begin using it.
```javascript
const SolidColor = require("photoshop").app.SolidColor;
```
--------------------------------
### Add a New Layer Comp
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/layercomps
Adds a new Layer Comp to the active document's collection. This is a basic usage example.
```javascript
const comp = await app.activeDocument.layerComps.add();
```
--------------------------------
### Modifying Text Content and Type
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/textitem
Demonstrates how to get and set the text content, check if it's point text, and convert it to paragraph text.
```javascript
textItem.contents; // "Lorem Ipsum"
textItem.contents = "Hello World";
textItem.isPointText; // true
await textItem.convertToParagraphText();
```
--------------------------------
### Include Files and Global Declarations for C++ SDK
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/cpp-pluginsdk
Essential includes and global variable declarations required for C++ SDK to UXP messaging.
```c
// Include these
#include "PIActions.h" // For PIActionDescriptor
#include "PIUXPSuite.h" // For messaging
// Your globals
SPBasicSuite * sSPBasic = NULL; // This is passed to your main function
SPPluginRef gPlugInRef = NULL; // This is passed to your main function
PsUXPSuite1* sUxpProcs = NULL; // You acquire this using sSPBasic
PSActionDescriptorProcs* sDescriptorProcs = NULL; // You acquire this using sSPBasic
```
--------------------------------
### Get Color Sampler Collection Length
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/colorsamplers
Retrieves the number of color samplers currently in the collection. A new document initially has a length of 0.
```javascript
app.activeDocument.colorSamplers.length;
```
--------------------------------
### sampleColor
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/document
Samples a SolidColor object from the document at a specified position. This is an asynchronous operation that returns a Promise.
```APIDOC
## sampleColor
### Description
Returns a SolidColor object sampled from the document at the given position. This is an asynchronous operation.
### Method
`sampleColor(position: {x: number, y: number}): Promise`
### Parameters
#### Path Parameters
- **position** (object) - Required - The point to sample `{x: number, y: number}`.
- **position.x** (number) - Required - The horizontal coordinate in pixels.
- **position.y** (number) - Required - The vertical coordinate in pixels.
### Request Example
```javascript
let col = await app.activeDocument.sampleColor({x: 100, y: 100});
console.log(col.rgb);
// { red: 233, green: 179, blue: 135, hexValue: "E9B387" }
```
### Response
#### Success Response
- **SolidColor** - An object representing the sampled color.
- **NoColor** - Indicates no color could be sampled.
#### Response Example
```json
{
"red": 233,
"green": 179,
"blue": 135,
"hexValue": "E9B387"
}
```
```
--------------------------------
### Create a Text Layer with Options
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/objects/createoptions/textlayercreateoptions
Demonstrates how to create a new text layer with specified content, font size, and position. The default position is the center of the document; explicitly setting `position` uses the bottom-left corner.
```javascript
const options = {
name: "myTextLayer",
contents: "Hello, World!",
fontSize: 24,
position: {x: 200, y: 300}
};
await require('photoshop').app.activeDocument.createTextLayer(options);
```
--------------------------------
### Get Image Pixels with Bounds
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/imaging
Retrieves pixel data for a specified region of an image. Ensure the sourceBounds and targetSize are correctly defined for the desired output.
```javascript
const image = await photoshop.app.activeDocument.getPixelData({
sourceBounds: { left: 0, top: 0, right: 300, bottom: 300 },
targetSize: { height: 100 }
});
```
--------------------------------
### Get Layer Group Contents (Sync)
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Synchronously retrieves a list of layers contained within a specified layer group. Requires both documentID and layerID.
```javascript
core.getLayerGroupContentsSync({ documentID: 123, layerID: 9 });
```
--------------------------------
### Get Layer Group Contents (Async)
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Asynchronously retrieves a list of layers contained within a specified layer group. Requires both documentID and layerID.
```javascript
await core.getLayerGroupContents({ documentID: 123, layerID: 9 });
```
--------------------------------
### Create and Manipulate Photoshop Document with UXP Script
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/uxpscripting
This script demonstrates creating a new document, adding a layer, filling it with foreground color, renaming the layer, applying the Clouds filter, and grouping the layer using the UXP Photoshop DOM API.
```javascript
const app = require('photoshop').app;
app.documents.add();
app.activeDocument.createLayer({ name: "not descriptive name"});
require('photoshop').action.batchPlay([{"_obj":"fill", "using":{"_enum":"fillContents","_value":"foregroundColor"}
}], {});
app.activeDocument.layers[0].applyClouds();
app.activeDocument.layers[0].name = 'cloudy';
app.activeDocument.createLayerGroup({fromLayers: app.activeDocument.layers[0]});
```
--------------------------------
### Import photoshopCore Module
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Import the core module from the photoshop library. This is typically the first step before using any of its functions.
```javascript
const {core} = require('photoshop');
```
--------------------------------
### Get Active Tool Information
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Retrieves information about the currently active tool in Photoshop, including its class ID, modal state, key, and title.
```javascript
const { title } = await core.getActiveTool();
```
--------------------------------
### Get All Layer Comps by Name
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/layercomps
Retrieves all Layer Comps from the active document that match the specified name. This is useful for finding specific layer compositions.
```javascript
const comps = await app.activeDocument.layerComps.getAllByName("MyCompName");
```
--------------------------------
### Create a Text Layer
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/document
Creates a new text layer. Options can include name, contents, and font size.
```javascript
await doc.createLayer(
Constants.LayerKind.TEXT,
{ name: "message", contents: "Hello World" }
);
```
--------------------------------
### PhotoshopImageData dispose Example
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/imaging
Releases image data held by a PhotoshopImageData instance to free up memory. This method should be called when image data is no longer needed.
```javascript
const imageData = await imaging.createImageDataFromBuffer( arrayBuffer, options );
// perhaps a putPixels call
imageData.dispose();
```
--------------------------------
### Listen for All Action Notifications
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
This snippet shows how to set up a listener to receive notifications for all Photoshop events and their associated descriptors. This is useful for debugging and understanding Photoshop's internal actions.
```javascript
action.addNotificationListener(
['all'],
(event, descriptor) => {
console.log("Event: " + event + " Descriptor: " + JSON.stringify(descriptor))
}
);
```
--------------------------------
### app.open
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/classes/photoshop
Opens a specified document in Photoshop. It can either open a document using a provided UXPFileEntry object or display the system's open file dialog if no entry is given.
```APIDOC
## app.open
### Description
Opens the specified document and returns the model. This API requires a UXPFileEntry object as its argument, or it will show the open file dialog.
### Method
Asynchronous function
### Parameters
#### Path Parameters
- **entry** (File) - Optional - The UXPFileEntry object representing the file to open.
### Request Example
```javascript
// Open a file given entry
let entry = await require('uxp').storage.localFileSystem.getFileForOpening()
const document = await app.open(entry);
// Show open file dialog
const document = await app.open();
```
```
--------------------------------
### Action Reference by ID
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/batchplay
An example of an action reference using the ID form to specify a document. This is recommended for stability as IDs do not change during a Photoshop session.
```json
{_ref: "document", _id: 123}
```
--------------------------------
### Get Menu Command Title
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopcore
Retrieves the localized title of a menu command item using its ID. Useful for displaying menu item names dynamically.
```javascript
const renameLayerStr = await core.getMenuCommandTitle({ commandID: 2983 });
```
--------------------------------
### batchPlay
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/media/photoshopaction
Performs a batchPlay call with the provided commands, similar to `executeAction` in ExtendScript.
```APIDOC
## batchPlay
### Description
Performs a batchPlay call with the provided commands. Equivalent to an `executeAction` in ExtendScript.
### Method
`Promise`
### Parameters
#### Parameters
- **commands** (ActionDescriptor[]) - Required - The commands to execute.
- **options?** (BatchPlayCommandOptions) - Optional - Options for the batchPlay command.
```
--------------------------------
### Get Hyphenation Features
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/objects/options/hyphenationproperties
Retrieves the current hyphenation settings for the active text item's paragraph style. This returns an object containing all hyphenation properties.
```javascript
const textItem = app.activeDocument.activeLayers[0].textItem;
textItem.paragraphStyle.hyphenationFeatures;
// {
// wordsLongerThan: 5,
// afterFirst: 2,
// beforeLast: 2,
// limit: 2,
// zone: 36,
// capitalWords: true
// }
```
--------------------------------
### Access History States by Index
Source: https://adobedocs.github.io/uxp-photoshop/ps_reference/changelog
Access specific history states using array-like indexing. This example retrieves the third history state of the active document.
```javascript
activeDocument.historyStates[2]
```