Photopea Embedded Editor Skill
Using photopea.js (yikuansun/PhotopeaAPI) in Websites & Apps
When to Use This Skill
Use this skill for every task that involves:
- Embedding Photopea as an image editor inside a webpage or web app
- Controlling an embedded Photopea instance from your JavaScript code
- Automating image editing workflows from a host page (open files, run scripts, export results)
- Building an image editing feature into your product using Photopea as the engine
- Writing scripts to manipulate documents, layers, text, selections, filters, colors, and paths
Do NOT use raw postMessage wiring — always use photopea.js as the wrapper.
Library: photopea.js
photopea.js is a Promises-based JavaScript wrapper around the Photopea Live Messaging API.
Repository: https://github.com/yikuansun/PhotopeaAPI
npm package: https://www.npmjs.com/package/photopea
Installation
CDN (no build step)
<script src="https://cdn.jsdelivr.net/npm/photopea@1.1.1/dist/photopea.min.js"></script>
Self-hosted
<script src="./photopea.min.js"></script>
npm (Webpack / Vite / Rollup)
npm install photopea
import Photopea from "photopea";
Core API: The Photopea Class
| Method |
Description |
Photopea.createEmbed(container) |
Creates + injects the iframe, resolves when ready |
new Photopea(window.parent) |
Plugin mode: wrap the parent window |
pea.runScript(script) |
Run JS string inside Photopea; returns output array |
pea.loadAsset(arrayBuffer) |
Load binary file (image, font, brush, etc.) |
pea.openFromURL(url, asSmart) |
Open remote URL as new doc or smart object layer |
pea.exportImage(type) |
Export current doc; returns Blob ("png" or "jpg") |
All methods return Promises — always await or .then().
Step 1 — Embed
The container <div> must have a fixed width and height before calling createEmbed.
<div id="editor" style="width:1000px; height:650px;"></div>
<script src="https://cdn.jsdelivr.net/npm/photopea@1.1.1/dist/photopea.min.js"></script>
<script>
Photopea.createEmbed(document.getElementById("editor")).then(async (pea) => {
// pea is ready
});
</script>
React:
import { useEffect, useRef } from "react";
import Photopea from "photopea";
export default function Editor() {
const containerRef = useRef(null);
const peaRef = useRef(null);
useEffect(() => {
if (!containerRef.current || peaRef.current) return;
Photopea.createEmbed(containerRef.current).then((pea) => {
peaRef.current = pea;
});
}, []);
return <div ref={containerRef} style={{ width: "100%", height: "650px" }} />;
}
Step 2 — Opening Files
// Remote URL → new document
await pea.openFromURL("https://example.com/design.psd", false);
// Remote URL → smart object layer inside current document
await pea.openFromURL("https://example.com/overlay.png", true);
// Local file (user input → ArrayBuffer → loadAsset)
document.getElementById("fileInput").addEventListener("change", async (e) => {
const buf = await e.target.files[0].arrayBuffer();
await pea.loadAsset(buf);
});
// Base64 data URI via runScript
await pea.runScript(`app.open("data:image/png;base64,iVBORw0...");`);
Step 3 — Running Scripts
runScript sends a JS string, returns an array of app.echoToOE(...) values + "done" last.
const result = await pea.runScript(`app.echoToOE("hello");`);
// result → ["hello", "done"]
// Return structured data
const out = await pea.runScript(`
app.echoToOE(JSON.stringify({
width: app.activeDocument.width,
height: app.activeDocument.height,
layers: app.activeDocument.layers.length
}));
`);
const info = JSON.parse(out[0]);
Step 4 — Exporting
// PNG Blob (via exportImage)
const blob = await pea.exportImage("png");
document.getElementById("preview").src = URL.createObjectURL(blob);
// JPEG Blob
const blob = await pea.exportImage("jpg");
// WebP / PSD / quality-controlled JPEG via saveToOE
const result = await pea.runScript(`app.activeDocument.saveToOE("webp:0.85");`);
const webpBlob = new Blob([result[0]], { type: "image/webp" });
const result = await pea.runScript(`app.activeDocument.saveToOE("psd:true");`);
const psdBlob = new Blob([result[0]], { type: "application/octet-stream" });
// Trigger download
async function download(pea, filename = "export.png") {
const blob = await pea.exportImage("png");
const a = Object.assign(document.createElement("a"), {
href: URL.createObjectURL(blob),
download: filename
});
a.click();
}
Export format strings for saveToOE:
| String |
Format |
"png" |
PNG lossless |
"jpg" |
JPEG default |
"jpg:0.8" |
JPEG quality 0.0–1.0 |
"webp:0.7" |
WebP quality 0.0–1.0 |
"psd" |
Full PSD |
"psd:true" |
Minified PSD |
"svg:true" |
SVG |
Step 5 — Loading Assets
// Font
const buf = await (await fetch("https://example.com/MyFont.otf")).arrayBuffer();
await pea.loadAsset(buf);
// Now usable in textItem.font
// Brush
await pea.loadAsset(await (await fetch("Nature.ABR")).arrayBuffer());
// Gradient
await pea.loadAsset(await (await fetch("Gradients.GRD")).arrayBuffer());
Step 6 — Plugin Mode
// Your page is inside Photopea's sidebar iframe
const pea = new Photopea(window.parent);
const out = await pea.runScript(`app.echoToOE(app.activeDocument.width);`);
console.log("Width:", out[0]);
// Load an asset from your plugin
const buf = await (await fetch("https://my-assets.com/sticker.png")).arrayBuffer();
await pea.loadAsset(buf);
Plugin config:
{
"environment": {
"plugins": [{
"name": "My Plugin",
"url": "https://my-plugin.example.com",
"icon": "===https://my-plugin.example.com/icon.png"
}]
}
}
Utility Patterns
addImageAndWait — robust async layer insertion
async function addImageAndWait(pea, imgURI) {
let count = "done";
while (count === "done")
count = (await pea.runScript(`app.echoToOE(app.activeDocument.layers.length)`))[0];
count = parseInt(count);
const imageUrlLiteral = JSON.stringify(imgURI);
await pea.runScript(`app.open(${imageUrlLiteral}, null, true);`);
return new Promise((resolve) => {
const check = async () => {
const n = parseInt((await pea.runScript(
`app.echoToOE(app.activeDocument.layers.length)`
))[0]);
n === count + 1 ? resolve() : setTimeout(check, 50);
};
check();
});
}
getDocumentAsImage — returns <img> element
async function getDocumentAsImage(pea) {
const result = await pea.runScript(`app.activeDocument.saveToOE('png')`);
return new Promise((resolve) => {
const fr = new FileReader();
fr.addEventListener("load", (e) => {
const img = new Image(); img.src = e.target.result; resolve(img);
});
fr.readAsDataURL(new Blob([result[0]], { type: "image/png" }));
});
}
Real-World Patterns
Pattern A — Open + Export UI
<input type="file" id="fileInput" accept="image/*,.psd">
<button id="exportBtn">Export PNG</button>
<div id="editor" style="width:100%;height:600px;"></div>
<script src="https://cdn.jsdelivr.net/npm/photopea@1.1.1/dist/photopea.min.js"></script>
<script>
let pea;
Photopea.createEmbed(document.getElementById("editor")).then(p => pea = p);
document.getElementById("fileInput").addEventListener("change", async e => {
await pea.loadAsset(await e.target.files[0].arrayBuffer());
});
document.getElementById("exportBtn").addEventListener("click", async () => {
const blob = await pea.exportImage("png");
const a = Object.assign(document.createElement("a"), {
href: URL.createObjectURL(blob), download: "export.png"
});
a.click();
});
</script>
Pattern B — Template + Text Edit + Export
async function generateCard(pea, name, tagline) {
await pea.openFromURL("https://example.com/card.psd", false);
const nameLiteral = JSON.stringify(name);
const taglineLiteral = JSON.stringify(tagline);
await pea.runScript(`
app.activeDocument.layers.getByName("Name").textItem.contents = ${nameLiteral};
app.activeDocument.layers.getByName("Tagline").textItem.contents = ${taglineLiteral};
`);
return await pea.exportImage("png");
}
Pattern C — Batch Watermark
async function batchWatermark(pea, imageURLs, watermarkURL) {
const results = [];
for (const url of imageURLs) {
await pea.openFromURL(url, false);
await pea.openFromURL(watermarkURL, true);
await pea.runScript(`
var doc = app.activeDocument, wm = doc.activeLayer;
wm.translate(doc.width - wm.bounds[2] - 20, doc.height - wm.bounds[3] - 20);
wm.opacity = 70;
`);
results.push(await pea.exportImage("png"));
await pea.runScript(`app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);`);
}
return results;
}
FULL SCRIPTING API REFERENCE
All code in this section runs inside pea.runScript("...") strings.
Photopea implements the Adobe Photoshop CC 2015 JavaScript scripting interface.
Any Photoshop script targeting that version should work in Photopea.
app — Application Object
Properties
| Property |
Type |
R/W |
Description |
app.activeDocument |
Document |
R/W |
The currently active document |
app.documents |
Documents |
R |
Collection of all open documents |
app.documents.length |
number |
R |
Count of open documents |
app.documents[i] |
Document |
R |
Access by zero-based index |
app.foregroundColor |
SolidColor |
R/W |
Current foreground color |
app.backgroundColor |
SolidColor |
R/W |
Current background color |
app.preferences.rulerUnits |
Units |
R/W |
Units.PIXELS, Units.CM, Units.INCHES, Units.MM, Units.PICAS, Units.POINTS, Units.PERCENT |
app.preferences.typeUnits |
TypeUnits |
R/W |
TypeUnits.PIXELS, TypeUnits.MM, TypeUnits.POINTS |
app.displayDialogs |
DialogModes |
R/W |
DialogModes.NO, DialogModes.ALL, DialogModes.ERROR |
Methods
| Method |
Description |
app.open(url) |
Open URL as new document |
app.open(url, null, true) |
Open URL as smart object layer in active document |
app.echoToOE(string) |
Photopea extension — send string to host page (captured by runScript) |
app.showWindow("magiccut") |
Photopea extension — open Magic Cut panel |
app.showWindow("vbitmap") |
Photopea extension — open Vectorize Bitmap panel |
app.UI.zoomIn() |
Zoom in |
app.UI.zoomOut() |
Zoom out |
app.UI.fitTheArea() |
Fit canvas to viewport |
app.UI.pixelToPixel() |
100% zoom |
app.UI.switchFullscreen() |
Toggle fullscreen |
app.UI.scroll(dx, dy) |
Scroll by delta |
app.UI.scrollTo(x, y) |
Scroll to absolute position |
Important: Always set ruler units to pixels at the start of any script that uses pixel measurements:
var savedUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// ... your code ...
app.preferences.rulerUnits = savedUnits;
Document — Document Object
Access via app.activeDocument or app.documents[i].
Properties
| Property |
Type |
R/W |
Description |
width |
number |
R |
Document width in current ruler units |
height |
number |
R |
Document height in current ruler units |
resolution |
number |
R |
DPI (pixels per inch) |
name |
string |
R/W |
Photopea extension — display label (no history step) |
source |
string |
R/W |
Photopea extension — file origin URL or "local,X,NAME" |
mode |
DocumentMode |
R |
DocumentMode.RGB, GRAYSCALE, CMYK, LAB, BITMAP, INDEXEDCOLOR, MULTICHANNEL |
bitsPerChannel |
BitsPerChannelType |
R |
BitsPerChannelType.EIGHT, SIXTEEN, THIRTYTWO |
colorProfileName |
string |
R |
Name of embedded color profile |
activeLayer |
Layer/ArtLayer/LayerSet |
R/W |
Set to activate a layer |
currentLayer |
ArtLayer |
R/W |
Alias for activeLayer |
layers |
Layers |
R |
All top-level layers (both art + group) |
artLayers |
ArtLayers |
R |
All top-level art layers only |
layerSets |
LayerSets |
R |
All top-level group layers only |
selection |
Selection |
R |
The current selection |
channels |
Channels |
R |
All channels |
historyStates |
HistoryStates |
R |
Undo history |
activeHistoryState |
HistoryState |
R/W |
Current history position |
layerComps |
LayerComps |
R |
Layer comps collection |
guides |
Guides |
R |
Guides collection |
pathItems |
PathItems |
R |
Vector paths |
id |
number |
R |
Unique document ID |
saved |
boolean |
R |
Whether document has unsaved changes |
quickMaskMode |
boolean |
R |
Whether in Quick Mask mode |
backgroundLayer |
ArtLayer |
R |
The background layer |
pixelAspectRatio |
number |
R |
Custom pixel aspect ratio (0.1–10.0) |
histogram |
array |
R |
256-element histogram array |
Methods
| Method |
Signature |
Description |
resizeImage |
(w, h, res, resampleMethod) |
Resize image pixels. ResampleMethod: BICUBIC, BILINEAR, NEARESTNEIGHBOR, NONE, BICUBICSHARPER, BICUBICSMOOTHER |
resizeCanvas |
(w, h, anchor) |
Resize canvas without scaling. AnchorPosition: TOPLEFT, TOPCENTER, TOPRIGHT, MIDDLELEFT, MIDDLECENTER, MIDDLERIGHT, BOTTOMLEFT, BOTTOMCENTER, BOTTOMRIGHT |
rotateCanvas |
(degrees) |
Rotate entire canvas. Positive = clockwise |
flipCanvas |
(direction) |
Direction.HORIZONTAL or Direction.VERTICAL |
crop |
([x1,y1,x2,y2], angle, w, h) |
Crop canvas. Angle and dimensions are optional |
trim |
(trimType, top, left, bottom, right) |
Trim transparent/background-color borders. TrimType: TRANSPARENT, TOPLEFT, BOTTOMRIGHT |
revealAll |
() |
Expand canvas to show clipped content |
flatten |
() |
Merge all layers into one |
mergeVisibleLayers |
() |
Merge all visible layers |
rasterizeAllLayers |
() |
Rasterize all vector/text layers |
changeMode |
(mode, options) |
Convert color mode (e.g., ChangeMode.GRAYSCALE) |
convertProfile |
(profileName, renderingIntent, blackPointCompensation, dither) |
Convert color profile |
duplicate |
(name, mergedLayers) |
Duplicate the document |
close |
(saveOptions) |
Close document. SaveOptions: DONOTSAVECHANGES, SAVECHANGES, PROMPTTOSAVECHANGES |
save |
() |
Save (requires server config in embed) |
saveToOE |
(format) |
Photopea extension — send binary to host. Formats: "png", "jpg:0.8", "webp:0.7", "psd:true", "svg:true" |
clearHistory |
() |
Photopea extension — clear undo history to free RAM |
exportDocument |
(file, exportType, options) |
Export to filesystem (triggers ZIP). ExportType: SAVEFORWEB |
paste |
(intoSelection) |
Paste clipboard into document |
suspendHistory |
(historyName, callback) |
Wrap multiple ops in one history state |
Practical examples:
var doc = app.activeDocument;
// Resize image to 1920×1080 at 72dpi bicubic
doc.resizeImage(1920, 1080, 72, ResampleMethod.BICUBIC);
// Expand canvas to 2000px wide, keeping content centered
doc.resizeCanvas(2000, doc.height, AnchorPosition.MIDDLECENTER);
// Crop to a region
doc.crop([100, 100, 900, 600]);
// Trim transparent edges
doc.trim(TrimType.TRANSPARENT, true, true, true, true);
// Flip horizontal
doc.flipCanvas(Direction.HORIZONTAL);
// Change to grayscale
doc.changeMode(ChangeMode.GRAYSCALE);
// One undo step for many operations
doc.suspendHistory("Batch Edit", "action");
// (Inside Photopea, all ops become one history state)
// Export PNG to filesystem (triggers ZIP download)
var opts = new ExportOptionsSaveForWeb();
opts.format = SaveDocumentType.PNG;
opts.PNG8 = false;
opts.quality = 100;
doc.exportDocument(new File("/output.png"), ExportType.SAVEFORWEB, opts);
// Close without saving
doc.close(SaveOptions.DONOTSAVECHANGES);
Layers / ArtLayers / LayerSets Collections
These collections exist on Document, LayerSet (groups within groups), and can be iterated.
var doc = app.activeDocument;
// Access
doc.layers // all top-level (art + groups)
doc.artLayers // top-level art layers only
doc.layerSets // top-level group layers only
// By index (0 = topmost)
doc.layers[0]
doc.layers[doc.layers.length - 1] // bottommost
// By name (throws if not found)
doc.layers.getByName("Background")
doc.artLayers.getByName("Logo")
doc.layerSets.getByName("Header Group")
// Add
var newLayer = doc.artLayers.add(); // new blank art layer
var newGroup = doc.layerSets.add(); // new group
var innerLayer = newGroup.artLayers.add(); // layer inside a group
// Remove
doc.artLayers.getByName("Temp").remove();
// Iterate all layers recursively
function walkLayers(parent) {
for (var i = 0; i < parent.layers.length; i++) {
var l = parent.layers[i];
if (l.typename === "LayerSet") walkLayers(l);
else /* ArtLayer */ processLayer(l);
}
}
walkLayers(doc);
ArtLayer — Individual Layer
Properties
| Property |
Type |
R/W |
Description |
name |
string |
R/W |
Layer name |
visible |
boolean |
R/W |
Layer visibility |
opacity |
number |
R/W |
Layer opacity 0–100 |
fillOpacity |
number |
R |
Fill opacity 0–100 |
blendMode |
BlendMode |
R/W |
Blend mode (see enum below) |
kind |
LayerKind |
R/W |
Layer type (can set to LayerKind.TEXT on empty layer) |
textItem |
TextItem |
R |
Text object (only when kind === LayerKind.TEXT) |
bounds |
array |
R |
[left, top, right, bottom] in current ruler units |
parent |
Document/LayerSet |
R |
Containing object |
typename |
string |
R |
Always "ArtLayer" |
selected |
boolean |
R |
Photopea extension — is layer highlighted in panel |
isBackgroundLayer |
boolean |
R |
Is this the locked background layer |
grouped |
boolean |
R |
Is clipping mask applied |
pixelsLocked |
boolean |
R |
Pixels locked |
positionLocked |
boolean |
R |
Position locked |
transparentPixelsLocked |
boolean |
R |
Transparent pixels locked |
layerMaskDensity |
number |
R |
Layer mask density 0–100 |
layerMaskFeather |
number |
R |
Layer mask feather 0–250 |
vectorMaskDensity |
number |
R |
Vector mask density 0–100 |
vectorMaskFeather |
number |
R |
Vector mask feather 0–250 |
Transform Methods
| Method |
Signature |
Description |
translate |
(deltaX, deltaY) |
Move layer by offset |
rotate |
(angle, anchor) |
Rotate by degrees. AnchorPosition optional (default center) |
resize |
(widthPct, heightPct, anchor) |
Scale as percentage of current size |
rasterize |
(target) |
Rasterize. RasterizeType: ENTIRE, FILLCONTENT, LAYERCLIPPINGMASK, LINKEDLAYERS, SHAPE, TEXTCONTENTS, VECTORMASK |
Layer Management Methods
| Method |
Signature |
Description |
duplicate |
() |
Duplicate to same document, returns new layer |
duplicate |
(doc, placement) |
Duplicate to another document |
remove |
() |
Delete the layer |
merge |
() |
Merge down; returns the merged ArtLayer |
move |
(relativeLayer, placement) |
Reorder. ElementPlacement: PLACEBEFORE, PLACEAFTER, PLACEATBEGINNING, PLACEATEND, INSIDE |
copy |
(merged) |
Copy to clipboard |
cut |
() |
Cut to clipboard |
clear |
() |
Cut without clipboard |
Adjustment Methods on ArtLayer
| Method |
Signature |
Description |
adjustBrightnessContrast |
(brightness, contrast) |
Brightness -100–100, Contrast -100–100 |
adjustColorBalance |
(shadows, midtones, highlights, preserveLuminosity) |
Each is [cyan-red, magenta-green, yellow-blue] array |
adjustCurves |
(curveShape) |
Array of [input,output] pairs per channel |
adjustLevels |
(inputRangeStart, inputRangeEnd, gamma, outputRangeStart, outputRangeEnd) |
Levels adjustment |
autoLevels |
() |
Auto levels |
autoContrast |
() |
Auto contrast |
desaturate |
() |
Convert to grayscale values in current mode |
equalize |
() |
Equalize brightness distribution |
invert |
() |
Invert pixel colors |
posterize |
(levels) |
Posterize (2–255 levels) |
threshold |
(level) |
B&W threshold (1–255) |
shadowHighlight |
(shadowAmount, shadowWidth, shadowRadius, highlightAmount, highlightWidth, highlightRadius, colorCorrection, midtoneContrast, blackClip, whiteClip) |
Shadows/Highlights |
photoFilter |
(fillColor, density, luminosity) |
Photo filter |
mixChannels |
(outputChannels, monochrome) |
Channel mixer |
selectiveColor |
(colors, cyan, magenta, yellow, black, method) |
Selective color |
Filter Methods on ArtLayer
| Method |
Signature |
Description |
applyGaussianBlur |
(radius) |
Gaussian blur (0.1–250 px radius) |
applyMotionBlur |
(angle, distance) |
Motion blur |
applyRadialBlur |
(amount, blurMethod, blurQuality) |
Radial blur |
applySmartBlur |
(radius, threshold, blurQuality, blurMode) |
Smart blur |
applyBlur |
() |
Simple blur |
applyBlurMore |
() |
Blur more |
applyUnSharpMask |
(amount, radius, threshold) |
Unsharp mask |
applySharpen |
() |
Sharpen |
applySharpenEdges |
() |
Sharpen edges |
applySharpenMore |
() |
Sharpen more |
applyAddNoise |
(amount, distribution, monochromatic) |
Add noise. NoiseDistribution: GAUSSIAN, UNIFORM |
applyDespeckle |
() |
Despeckle |
applyDustAndScratches |
(radius, threshold) |
Dust and scratches |
applyMedianNoise |
(radius) |
Median noise reduction |
applyMaximum |
(radius) |
Maximum filter (dilate) |
applyMinimum |
(radius) |
Minimum filter (erode) |
applyHighPass |
(radius) |
High pass |
applyOffset |
(horizontal, vertical, undefinedAreas) |
Offset. UndefinedAreas: SETTOBACKGROUND, WRAPAROUND, REPEATEDGEPIXELS |
applyRipple |
(amount, size) |
Ripple. RippleSize: SMALL, MEDIUM, LARGE |
applyWave |
(generators, minWavelength, maxWavelength, minAmplitude, maxAmplitude, horizScale, vertScale, waveType, undefinedAreas, randomSeed) |
Wave filter |
applyZigZag |
(amount, ridges, style) |
Zig-Zag |
applyTwirl |
(angle) |
Twirl |
applyPolarCoordinates |
(conversion) |
Polar coordinates |
applySpherize |
(amount, mode) |
Spherize |
applyPinch |
(amount) |
Pinch (-100–100) |
applyShear |
(curve, undefinedAreas) |
Shear |
applyDisplace |
(horizontalScale, verticalScale, displacementType, undefinedAreas, displacementMapFile) |
Displace |
applyClouds |
() |
Render Clouds |
applyDifferenceClouds |
() |
Difference Clouds |
applyLensFlare |
(brightness, flareCenter, lensType) |
Lens Flare. LensType: ZOOMWIDE, ZOOMNORMAL, MOVIE |
applyDiffuseGlow |
(graininess, glowAmount, clearAmount) |
Diffuse Glow |
applyGlassEffect |
(distortion, smoothness, scaling, invert, texture, textureFile) |
Glass |
applyOceanRipple |
(size, magnitude) |
Ocean Ripple |
applyLensBlur |
(source, focalDistance, invertDepthMap, shape, radius, bladeCurvature, rotation, brightness, threshold, amount, distribution, monochromatic) |
Lens Blur |
applyAverage |
() |
Average blur |
applyDeInterlace |
(eliminateFields, createFields) |
De-interlace |
applyNTSC |
() |
NTSC colors |
applyCustomFilter |
(characteristics, scale, offset) |
Custom filter (5×5 matrix) |
applyTextureFill |
(textureFile) |
Texture fill |
applyStyle |
(styleName) |
Apply a layer style preset by name |
photoFilter |
(fillColor, density, luminosity) |
Photo Filter |
Practical examples:
var layer = app.activeDocument.activeLayer;
// Move to absolute position (layer.bounds[0] = current left edge)
layer.translate(200 - layer.bounds[0], 100 - layer.bounds[1]);
// Rotate 45° around center
layer.rotate(45);
// Scale to 50% keeping center
layer.resize(50, 50, AnchorPosition.MIDDLECENTER);
// Gaussian blur radius 10
layer.applyGaussianBlur(10);
// Unsharp mask
layer.applyUnSharpMask(50, 2, 0);
// Levels: input 0–200, gamma 1.2, output 0–255
layer.adjustLevels(0, 200, 1.2, 0, 255);
// Brightness +20, Contrast +10
layer.adjustBrightnessContrast(20, 10);
// Invert
layer.invert();
// Rasterize text
layer.rasterize(RasterizeType.TEXTCONTENTS);
// Duplicate layer
var copy = layer.duplicate();
copy.name = "Layer Copy";
// Move layer below another
var target = doc.layers.getByName("Background");
layer.move(target, ElementPlacement.PLACEAFTER);
LayerSet — Group Layer
A LayerSet is a folder/group in the Layers panel. It has the same layer management methods as Document.
Properties
| Property |
Type |
R/W |
Description |
name |
string |
R/W |
Group name |
visible |
boolean |
R/W |
Group visibility |
opacity |
number |
R/W |
Group opacity 0–100 |
blendMode |
BlendMode |
R/W |
Group blend mode |
bounds |
array |
R |
Bounding box [left,top,right,bottom] |
layers |
Layers |
R |
All layers inside this group |
artLayers |
ArtLayers |
R |
Art layers inside this group |
layerSets |
LayerSets |
R |
Sub-groups inside this group |
parent |
Document/LayerSet |
R |
Parent container |
typename |
string |
R |
Always "LayerSet" |
Methods
Same as Document for layer management: layers.add(), artLayers.add(), layerSets.add(), .getByName(), plus duplicate(), remove(), move().
// Create group with layers inside
var group = doc.layerSets.add();
group.name = "Product Card";
var bgLayer = group.artLayers.add(); bgLayer.name = "Background";
var textLayer = group.artLayers.add(); textLayer.kind = LayerKind.TEXT;
textLayer.textItem.contents = "Buy Now";
textLayer.textItem.size = 36;
// Collapse/expand group (Photopea specific, not in standard DOM)
// Use visibility as workaround
// Get specific layer inside a group
var innerLayer = doc.layerSets.getByName("Header Group").artLayers.getByName("Title");
TextItem — Text Layer Content
Access via layer.textItem on any layer with layer.kind === LayerKind.TEXT.
Core Properties (most commonly used)
| Property |
Type |
R/W |
Description |
contents |
string |
R/W |
The actual text content |
font |
string |
R/W |
Font PostScript name (e.g. "ArialMT", "Verdana-Bold") |
size |
number |
R/W |
Font size in points |
color |
SolidColor |
R/W |
Text color |
position |
array |
R/W |
[x, y] origin of text (point text) or bounding box top-left |
justification |
Justification |
R/W |
Justification.LEFT, CENTER, RIGHT, FULLJUSTIFY |
kind |
TextType |
R/W |
TextType.POINTTEXT or TextType.PARAGRAPHTEXT |
width |
number |
R/W |
Width of bounding box (paragraph text only) |
height |
number |
R/W |
Height of bounding box (paragraph text only) |
direction |
Direction |
R/W |
Direction.HORIZONTAL or Direction.VERTICAL |
Typography Properties
| Property |
Type |
R/W |
Description |
leading |
number |
R/W |
Line spacing in points |
tracking |
number |
R/W |
Letter spacing -1000–10000 (1000 = 1 em) |
horizontalScale |
number |
R/W |
Horizontal scaling 0–1000% |
verticalScale |
number |
R/W |
Vertical scaling 0–1000% |
baselineShift |
number |
R/W |
Baseline offset in points |
capitalization |
Case |
R/W |
Case.NORMAL, ALLCAPS, SMALLCAPS |
fauxBold |
boolean |
R/W |
Simulated bold |
fauxItalic |
boolean |
R/W |
Simulated italic |
underline |
UnderlineType |
R/W |
UnderlineType.NONE, UNDERLINELEFT, UNDERLINERIGHT |
strikeThru |
StrikeThruType |
R/W |
StrikeThruType.NONE, STRIKEBOX, STRIKEHEIGHT |
antiAliasMethod |
AntiAlias |
R/W |
AntiAlias.NONE, SHARP, CRISP, STRONG, SMOOTH |
autoKerning |
AutoKernType |
R/W |
AutoKernType.MANUAL, METRICS, OPTICAL |
language |
Language |
R/W |
Language.ENGLISH, etc. |
ligatures |
boolean |
R/W |
Enable ligatures |
alternateLigatures |
boolean |
R/W |
Enable alternate ligatures |
oldStyle |
boolean |
R/W |
Old-style numerals |
noBreak |
boolean |
R/W |
Prevent line breaks in this text |
useAutoLeading |
boolean |
R/W |
Use font's built-in leading |
autoLeadingAmount |
number |
R/W |
Auto leading percentage 0.01–5000 |
hyphenation |
boolean |
R/W |
Enable hyphenation |
Paragraph Properties
| Property |
Type |
R/W |
Description |
leftIndent |
number |
R/W |
Left indent -1296–1296 |
rightIndent |
number |
R/W |
Right indent -1296–1296 |
firstLineIndent |
number |
R/W |
First line indent -1296–1296 |
spaceBefore |
number |
R/W |
Space before paragraph -1296–1296 |
spaceAfter |
number |
R/W |
Space after paragraph -1296–1296 |
hangingPuntuation |
boolean |
R/W |
Roman hanging punctuation |
textComposer |
TextComposer |
R/W |
TextComposer.ADOBEEVERYLINE, ADOBESINGLELINE |
Warp Properties
| Property |
Type |
R/W |
Description |
warpStyle |
WarpStyle |
R/W |
WarpStyle.NONE, ARC, ARCH, BULGE, SHELLLOWER, SHELLUPPER, FLAG, WAVE, FISH, RISE, FISHEYE, INFLATE, SQUEEZE, TWIST |
warpDirection |
Direction |
R/W |
Direction.HORIZONTAL or Direction.VERTICAL |
warpBend |
number |
R/W |
Warp bend -100–100 |
warpHorizontalDistortion |
number |
R/W |
Horizontal distortion -100–100 |
warpVerticalDistortion |
number |
R/W |
Vertical distortion -100–100 |
Photopea Extensions
| Property |
Type |
Description |
totalTextStyle |
string |
JSON string with ALL style parameters of the text |
transform |
string |
JSON array — the affine transform matrix of the text |
Methods
| Method |
Description |
convertToShape() |
Convert text to a filled shape layer with text as clipping path |
createPath() |
Create work path from text outlines |
Practical examples:
var layer = doc.layers.getByName("Headline");
var text = layer.textItem;
// Set content
text.contents = "Hello World";
// Style
text.font = "Verdana-Bold";
text.size = 72;
text.color.rgb.hexValue = "FF0000"; // red
// Position point text at (50, 100)
text.position = [50, 100];
// Center align
text.justification = Justification.CENTER;
// Paragraph text with bounding box
text.kind = TextType.PARAGRAPHTEXT;
text.width = new UnitValue("400 pixels");
text.height = new UnitValue("200 pixels");
// Letter spacing
text.tracking = 100; // 10% spacing
// Scale text horizontally to 80%
text.horizontalScale = 80;
// Warp arc
text.warpStyle = WarpStyle.ARC;
text.warpBend = 30;
// Read all text styles as JSON (Photopea extension)
var styles = JSON.parse(text.totalTextStyle);
app.echoToOE(JSON.stringify(styles));
Creating a Text Layer from Scratch
app.preferences.rulerUnits = Units.PIXELS;
var layer = doc.artLayers.add();
layer.kind = LayerKind.TEXT; // Convert blank layer to text
layer.name = "My Title";
var text = layer.textItem;
text.contents = "Welcome";
text.font = "ArialMT";
text.size = 48;
text.justification = Justification.CENTER;
text.position = [doc.width / 2, 100];
var color = new SolidColor();
color.rgb.red = 255;
color.rgb.green = 255;
color.rgb.blue = 255;
text.color = color;
SolidColor — Color Object
// RGB (most common in Photopea)
var c = new SolidColor();
c.rgb.red = 255; // 0–255
c.rgb.green = 128;
c.rgb.blue = 0;
c.rgb.hexValue = "FF8000"; // Set via hex string (no #)
// CMYK
var c2 = new SolidColor();
c2.cmyk.cyan = 0; // 0–100
c2.cmyk.magenta = 50;
c2.cmyk.yellow = 100;
c2.cmyk.black = 0;
// Grayscale
var c3 = new SolidColor();
c3.gray.gray = 50; // 0–100
// HSB
var c4 = new SolidColor();
c4.hsb.hue = 30; // 0–360
c4.hsb.saturation = 100; // 0–100
c4.hsb.brightness = 100; // 0–100
// Lab
var c5 = new SolidColor();
c5.lab.l = 50; // 0–100
c5.lab.a = 20; // -128–127
c5.lab.b = 40; // -128–127
// Set as foreground color
app.foregroundColor = c;
// Use with selection fill
doc.selection.selectAll();
doc.selection.fill(c);
doc.selection.deselect();
Selection — Selection Object
Access via doc.selection.
Properties
| Property |
Type |
Description |
bounds |
array |
[left, top, right, bottom] bounding rectangle |
solid |
boolean |
Whether selection is a solid rectangle |
Methods
| Method |
Signature |
Description |
selectAll |
() |
Select entire document |
deselect |
() |
Remove selection |
invert |
() |
Invert the selection |
select |
(region, type, feather, antiAlias) |
Select polygon region. Region is array of [x,y] points. SelectionType: REPLACE, ADD, SUBTRACT, INTERSECT |
feather |
(radius) |
Feather the selection edges |
contract |
(radius) |
Contract (shrink) selection |
expand |
(radius) |
Expand selection |
grow |
(tolerance, antiAlias) |
Grow selection to similar adjacent pixels |
similar |
(tolerance, antiAlias) |
Select similar pixels throughout document |
smooth |
(radius) |
Smooth selection edges |
selectBorder |
(width) |
Select only the border of the current selection |
resize |
(widthPct, heightPct, anchor) |
Resize selection boundary |
rotate |
(angle, anchor) |
Rotate selection boundary |
translate |
(deltaX, deltaY) |
Move selection boundary |
fill |
(fillWith, mode, opacity, preserveTransparency) |
Fill selection with color or content. fillWith is SolidColor or string |
stroke |
(strokeColor, width, location, mode, opacity, preserveTransparency) |
Stroke selection border. StrokeLocation: INSIDE, OUTSIDE, CENTER |
copy |
(merged) |
Copy selection to clipboard |
cut |
() |
Cut selection to clipboard |
clear |
() |
Delete selection content |
load |
(from, type, invert) |
Load selection from channel |
store |
(into, type) |
Save selection as channel |
makeWorkPath |
(tolerance) |
Convert to work path |
Practical examples:
var sel = doc.selection;
// Rectangle select (top-left to bottom-right)
sel.select([[0,0],[500,0],[500,300],[0,300]]);
// Select all
sel.selectAll();
// Add to existing selection
sel.select([[600,0],[900,0],[900,300],[600,300]], SelectionType.ADD);
// Feather 10px
sel.feather(10);
// Contract by 5px
sel.contract(5);
// Fill with red
var red = new SolidColor();
red.rgb.red = 255; red.rgb.green = 0; red.rgb.blue = 0;
sel.fill(red);
// Stroke selection with black, 3px, inside
var black = new SolidColor();
black.rgb.hexValue = "000000";
sel.stroke(black, 3, StrokeLocation.INSIDE);
// Copy, paste as new layer
sel.copy();
doc.paste();
// Invert and delete (remove background)
sel.invert();
sel.clear();
sel.deselect();
BlendMode Enum — All Values
Used in layer.blendMode (string form in Photopea) and BlendMode constant (standard):
BlendMode Constant |
Photopea String |
Name |
BlendMode.NORMAL |
"norm" |
Normal |
BlendMode.DISSOLVE |
"diss" |
Dissolve |
BlendMode.DARKEN |
"dark" |
Darken |
BlendMode.MULTIPLY |
"mul " |
Multiply |
BlendMode.COLORBURN |
"idiv" |
Color Burn |
BlendMode.LINEARBURN |
"lbrn" |
Linear Burn |
BlendMode.DARKERCOLOR |
"dkCl" |
Darker Color |
BlendMode.LIGHTEN |
"lite" |
Lighten |
BlendMode.SCREEN |
"scrn" |
Screen |
BlendMode.COLORDODGE |
"div " |
Color Dodge |
BlendMode.LINEARDODGE |
"lddg" |
Linear Dodge (Add) |
BlendMode.LIGHTERCOLOR |
"lgCl" |
Lighter Color |
BlendMode.OVERLAY |
"over" |
Overlay |
BlendMode.SOFTLIGHT |
"sLit" |
Soft Light |
BlendMode.HARDLIGHT |
"hLit" |
Hard Light |
BlendMode.VIVIDLIGHT |
"vLit" |
Vivid Light |
BlendMode.LINEARLIGHT |
"lLit" |
Linear Light |
BlendMode.PINLIGHT |
"pLit" |
Pin Light |
BlendMode.HARDMIX |
"hMix" |
Hard Mix |
BlendMode.DIFFERENCE |
"diff" |
Difference |
BlendMode.EXCLUSION |
"smud" |
Exclusion |
BlendMode.SUBTRACT |
"fsub" |
Subtract |
BlendMode.DIVIDE |
"fdiv" |
Divide |
BlendMode.HUE |
"hue " |
Hue |
BlendMode.SATURATION |
"sat " |
Saturation |
BlendMode.COLOR |
"colr" |
Color |
BlendMode.LUMINOSITY |
"lum " |
Luminosity |
BlendMode.PASSTHROUGH |
"pass" |
Pass Through (groups only) |
// Use either form:
layer.blendMode = BlendMode.SCREEN; // constant
layer.blendMode = "scrn"; // string (Photopea internal form)
LayerKind Enum
| Constant |
Description |
LayerKind.NORMAL |
Regular pixel layer |
LayerKind.TEXT |
Text layer |
LayerKind.SMARTOBJECT |
Smart Object / linked layer |
LayerKind.SOLIDFILL |
Solid color fill layer |
LayerKind.GRADIENTFILL |
Gradient fill layer |
LayerKind.PATTERNFILL |
Pattern fill layer |
LayerKind.BRIGHTNESSCONTRAST |
Brightness/Contrast adjustment layer |
LayerKind.CURVES |
Curves adjustment layer |
LayerKind.LEVELS |
Levels adjustment layer |
LayerKind.HUESATURATION |
Hue/Saturation adjustment layer |
LayerKind.COLORBALANCE |
Color Balance adjustment layer |
LayerKind.CHANNELMIXER |
Channel Mixer adjustment layer |
LayerKind.GRADIENTMAP |
Gradient Map adjustment layer |
LayerKind.INVERSION |
Invert adjustment layer |
LayerKind.POSTERIZE |
Posterize adjustment layer |
LayerKind.THRESHOLD |
Threshold adjustment layer |
LayerKind.SELECTIVECOLOR |
Selective Color adjustment layer |
LayerKind.PHOTOFILTER |
Photo Filter adjustment layer |
LayerKind.EXPOSURE |
Exposure adjustment layer |
LayerKind.VIBRANCE |
Vibrance adjustment layer |
LayerKind.COLORLOOKUP |
Color Lookup adjustment layer |
LayerKind.LAYER3D |
3D layer (not generally useful in Photopea) |
LayerKind.VIDEO |
Video layer |
// Identify layer type
var layer = doc.activeLayer;
if (layer.kind === LayerKind.TEXT) /* text layer */;
if (layer.kind === LayerKind.SMARTOBJECT) /* smart object */;
if (layer.typename === "LayerSet") /* group */;
// Filter: collect all text layers recursively
var textLayers = [];
function collectText(parent) {
for (var i = 0; i < parent.layers.length; i++) {
var l = parent.layers[i];
if (l.typename === "LayerSet") collectText(l);
else if (l.kind === LayerKind.TEXT) textLayers.push(l);
}
}
collectText(doc);
AnchorPosition Enum
| Constant |
Position |
AnchorPosition.TOPLEFT |
Top left |
AnchorPosition.TOPCENTER |
Top center |
AnchorPosition.TOPRIGHT |
Top right |
AnchorPosition.MIDDLELEFT |
Middle left |
AnchorPosition.MIDDLECENTER |
Center |
AnchorPosition.MIDDLERIGHT |
Middle right |
AnchorPosition.BOTTOMLEFT |
Bottom left |
AnchorPosition.BOTTOMCENTER |
Bottom center |
AnchorPosition.BOTTOMRIGHT |
Bottom right |
ElementPlacement Enum
Used with layer.move(relativeObject, placement):
| Constant |
Effect |
ElementPlacement.PLACEBEFORE |
Above the target layer in the p |
…(truncated)
1---2name: photopea-embedded-editor3description: "Embed Photopea in web apps using photopea.js. Covers embedding, file I/O, scripting, exporting, layers, text, filters, and the full Photoshop-compatible API."4version: 1.0.05author:6 name: "sickn33 / Antigravity Community"7 github: sickn338tags: [photopea, embedded, editor]9category: uncategorized10platforms: [macos, linux, windows]11license: MIT12metadata:13 hermes:14 source: https://skillmd.com/skills/nous-hermeshub/photopea-embedded-editor15 upstream: "antigravity-awesome-skills"16 risk: "safe"17 date_added: "2026-05-20"18 original_author: "Antigravity Community"19---2021# Photopea Embedded Editor Skill22## Using photopea.js (yikuansun/PhotopeaAPI) in Websites & Apps2324---2526## When to Use This Skill2728Use this skill for **every task** that involves:29- Embedding Photopea as an image editor inside a webpage or web app30- Controlling an embedded Photopea instance from your JavaScript code31- Automating image editing workflows from a host page (open files, run scripts, export results)32- Building an image editing feature into your product using Photopea as the engine33- Writing scripts to manipulate documents, layers, text, selections, filters, colors, and paths3435**Do NOT** use raw `postMessage` wiring — always use `photopea.js` as the wrapper.3637---3839## Library: photopea.js4041`photopea.js` is a Promises-based JavaScript wrapper around the Photopea Live Messaging API.42Repository: https://github.com/yikuansun/PhotopeaAPI43npm package: https://www.npmjs.com/package/photopea4445### Installation4647**CDN (no build step)**48```html49<script src="https://cdn.jsdelivr.net/npm/photopea@1.1.1/dist/photopea.min.js"></script>50```5152**Self-hosted**53```html54<script src="./photopea.min.js"></script>55```5657**npm (Webpack / Vite / Rollup)**58```bash59npm install photopea60```61```js62import Photopea from "photopea";63```6465---6667## Core API: The `Photopea` Class6869| Method | Description |70|--------|-------------|71| `Photopea.createEmbed(container)` | Creates + injects the iframe, resolves when ready |72| `new Photopea(window.parent)` | Plugin mode: wrap the parent window |73| `pea.runScript(script)` | Run JS string inside Photopea; returns output array |74| `pea.loadAsset(arrayBuffer)` | Load binary file (image, font, brush, etc.) |75| `pea.openFromURL(url, asSmart)` | Open remote URL as new doc or smart object layer |76| `pea.exportImage(type)` | Export current doc; returns `Blob` (`"png"` or `"jpg"`) |7778All methods return Promises — always `await` or `.then()`.7980---8182## Step 1 — Embed8384The container `<div>` **must** have a fixed width and height before calling `createEmbed`.8586```html87<div id="editor" style="width:1000px; height:650px;"></div>88<script src="https://cdn.jsdelivr.net/npm/photopea@1.1.1/dist/photopea.min.js"></script>89<script>90 Photopea.createEmbed(document.getElementById("editor")).then(async (pea) => {91 // pea is ready92 });93</script>94```9596**React:**97```jsx98import { useEffect, useRef } from "react";99import Photopea from "photopea";100101export default function Editor() {102 const containerRef = useRef(null);103 const peaRef = useRef(null);104105 useEffect(() => {106 if (!containerRef.current || peaRef.current) return;107 Photopea.createEmbed(containerRef.current).then((pea) => {108 peaRef.current = pea;109 });110 }, []);111112 return <div ref={containerRef} style={{ width: "100%", height: "650px" }} />;113}114```115116---117118## Step 2 — Opening Files119120```js121// Remote URL → new document122await pea.openFromURL("https://example.com/design.psd", false);123124// Remote URL → smart object layer inside current document125await pea.openFromURL("https://example.com/overlay.png", true);126127// Local file (user input → ArrayBuffer → loadAsset)128document.getElementById("fileInput").addEventListener("change", async (e) => {129 const buf = await e.target.files[0].arrayBuffer();130 await pea.loadAsset(buf);131});132133// Base64 data URI via runScript134await pea.runScript(`app.open("data:image/png;base64,iVBORw0...");`);135```136137---138139## Step 3 — Running Scripts140141`runScript` sends a JS string, returns an array of `app.echoToOE(...)` values + `"done"` last.142143```js144const result = await pea.runScript(`app.echoToOE("hello");`);145// result → ["hello", "done"]146147// Return structured data148const out = await pea.runScript(`149 app.echoToOE(JSON.stringify({150 width: app.activeDocument.width,151 height: app.activeDocument.height,152 layers: app.activeDocument.layers.length153 }));154`);155const info = JSON.parse(out[0]);156```157158---159160## Step 4 — Exporting161162```js163// PNG Blob (via exportImage)164const blob = await pea.exportImage("png");165document.getElementById("preview").src = URL.createObjectURL(blob);166167// JPEG Blob168const blob = await pea.exportImage("jpg");169170// WebP / PSD / quality-controlled JPEG via saveToOE171const result = await pea.runScript(`app.activeDocument.saveToOE("webp:0.85");`);172const webpBlob = new Blob([result[0]], { type: "image/webp" });173174const result = await pea.runScript(`app.activeDocument.saveToOE("psd:true");`);175const psdBlob = new Blob([result[0]], { type: "application/octet-stream" });176177// Trigger download178async function download(pea, filename = "export.png") {179 const blob = await pea.exportImage("png");180 const a = Object.assign(document.createElement("a"), {181 href: URL.createObjectURL(blob),182 download: filename183 });184 a.click();185}186```187188**Export format strings for `saveToOE`:**189190| String | Format |191|--------|--------|192| `"png"` | PNG lossless |193| `"jpg"` | JPEG default |194| `"jpg:0.8"` | JPEG quality 0.0–1.0 |195| `"webp:0.7"` | WebP quality 0.0–1.0 |196| `"psd"` | Full PSD |197| `"psd:true"` | Minified PSD |198| `"svg:true"` | SVG |199200---201202## Step 5 — Loading Assets203204```js205// Font206const buf = await (await fetch("https://example.com/MyFont.otf")).arrayBuffer();207await pea.loadAsset(buf);208// Now usable in textItem.font209210// Brush211await pea.loadAsset(await (await fetch("Nature.ABR")).arrayBuffer());212213// Gradient214await pea.loadAsset(await (await fetch("Gradients.GRD")).arrayBuffer());215```216217---218219## Step 6 — Plugin Mode220221```js222// Your page is inside Photopea's sidebar iframe223const pea = new Photopea(window.parent);224225const out = await pea.runScript(`app.echoToOE(app.activeDocument.width);`);226console.log("Width:", out[0]);227228// Load an asset from your plugin229const buf = await (await fetch("https://my-assets.com/sticker.png")).arrayBuffer();230await pea.loadAsset(buf);231```232233Plugin config:234```json235{236 "environment": {237 "plugins": [{238 "name": "My Plugin",239 "url": "https://my-plugin.example.com",240 "icon": "===https://my-plugin.example.com/icon.png"241 }]242 }243}244```245246---247248## Utility Patterns249250### addImageAndWait — robust async layer insertion251```js252async function addImageAndWait(pea, imgURI) {253 let count = "done";254 while (count === "done")255 count = (await pea.runScript(`app.echoToOE(app.activeDocument.layers.length)`))[0];256 count = parseInt(count);257258 const imageUrlLiteral = JSON.stringify(imgURI);259 await pea.runScript(`app.open(${imageUrlLiteral}, null, true);`);260261 return new Promise((resolve) => {262 const check = async () => {263 const n = parseInt((await pea.runScript(264 `app.echoToOE(app.activeDocument.layers.length)`265 ))[0]);266 n === count + 1 ? resolve() : setTimeout(check, 50);267 };268 check();269 });270}271```272273### getDocumentAsImage — returns `<img>` element274```js275async function getDocumentAsImage(pea) {276 const result = await pea.runScript(`app.activeDocument.saveToOE('png')`);277 return new Promise((resolve) => {278 const fr = new FileReader();279 fr.addEventListener("load", (e) => {280 const img = new Image(); img.src = e.target.result; resolve(img);281 });282 fr.readAsDataURL(new Blob([result[0]], { type: "image/png" }));283 });284}285```286287---288289## Real-World Patterns290291### Pattern A — Open + Export UI292```html293<input type="file" id="fileInput" accept="image/*,.psd">294<button id="exportBtn">Export PNG</button>295<div id="editor" style="width:100%;height:600px;"></div>296<script src="https://cdn.jsdelivr.net/npm/photopea@1.1.1/dist/photopea.min.js"></script>297<script>298let pea;299Photopea.createEmbed(document.getElementById("editor")).then(p => pea = p);300301document.getElementById("fileInput").addEventListener("change", async e => {302 await pea.loadAsset(await e.target.files[0].arrayBuffer());303});304document.getElementById("exportBtn").addEventListener("click", async () => {305 const blob = await pea.exportImage("png");306 const a = Object.assign(document.createElement("a"), {307 href: URL.createObjectURL(blob), download: "export.png"308 });309 a.click();310});311</script>312```313314### Pattern B — Template + Text Edit + Export315```js316async function generateCard(pea, name, tagline) {317 await pea.openFromURL("https://example.com/card.psd", false);318 const nameLiteral = JSON.stringify(name);319 const taglineLiteral = JSON.stringify(tagline);320 await pea.runScript(`321 app.activeDocument.layers.getByName("Name").textItem.contents = ${nameLiteral};322 app.activeDocument.layers.getByName("Tagline").textItem.contents = ${taglineLiteral};323 `);324 return await pea.exportImage("png");325}326```327328### Pattern C — Batch Watermark329```js330async function batchWatermark(pea, imageURLs, watermarkURL) {331 const results = [];332 for (const url of imageURLs) {333 await pea.openFromURL(url, false);334 await pea.openFromURL(watermarkURL, true);335 await pea.runScript(`336 var doc = app.activeDocument, wm = doc.activeLayer;337 wm.translate(doc.width - wm.bounds[2] - 20, doc.height - wm.bounds[3] - 20);338 wm.opacity = 70;339 `);340 results.push(await pea.exportImage("png"));341 await pea.runScript(`app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);`);342 }343 return results;344}345```346347---348349# FULL SCRIPTING API REFERENCE350351> All code in this section runs **inside `pea.runScript("...")`** strings.352> Photopea implements the Adobe Photoshop CC 2015 JavaScript scripting interface.353> Any Photoshop script targeting that version should work in Photopea.354355---356357## `app` — Application Object358359### Properties360361| Property | Type | R/W | Description |362|----------|------|-----|-------------|363| `app.activeDocument` | Document | R/W | The currently active document |364| `app.documents` | Documents | R | Collection of all open documents |365| `app.documents.length` | number | R | Count of open documents |366| `app.documents[i]` | Document | R | Access by zero-based index |367| `app.foregroundColor` | SolidColor | R/W | Current foreground color |368| `app.backgroundColor` | SolidColor | R/W | Current background color |369| `app.preferences.rulerUnits` | Units | R/W | `Units.PIXELS`, `Units.CM`, `Units.INCHES`, `Units.MM`, `Units.PICAS`, `Units.POINTS`, `Units.PERCENT` |370| `app.preferences.typeUnits` | TypeUnits | R/W | `TypeUnits.PIXELS`, `TypeUnits.MM`, `TypeUnits.POINTS` |371| `app.displayDialogs` | DialogModes | R/W | `DialogModes.NO`, `DialogModes.ALL`, `DialogModes.ERROR` |372373### Methods374375| Method | Description |376|--------|-------------|377| `app.open(url)` | Open URL as new document |378| `app.open(url, null, true)` | Open URL as smart object layer in active document |379| `app.echoToOE(string)` | **Photopea extension** — send string to host page (captured by `runScript`) |380| `app.showWindow("magiccut")` | **Photopea extension** — open Magic Cut panel |381| `app.showWindow("vbitmap")` | **Photopea extension** — open Vectorize Bitmap panel |382| `app.UI.zoomIn()` | Zoom in |383| `app.UI.zoomOut()` | Zoom out |384| `app.UI.fitTheArea()` | Fit canvas to viewport |385| `app.UI.pixelToPixel()` | 100% zoom |386| `app.UI.switchFullscreen()` | Toggle fullscreen |387| `app.UI.scroll(dx, dy)` | Scroll by delta |388| `app.UI.scrollTo(x, y)` | Scroll to absolute position |389390**Important:** Always set ruler units to pixels at the start of any script that uses pixel measurements:391```js392var savedUnits = app.preferences.rulerUnits;393app.preferences.rulerUnits = Units.PIXELS;394// ... your code ...395app.preferences.rulerUnits = savedUnits;396```397398---399400## `Document` — Document Object401402Access via `app.activeDocument` or `app.documents[i]`.403404### Properties405406| Property | Type | R/W | Description |407|----------|------|-----|-------------|408| `width` | number | R | Document width in current ruler units |409| `height` | number | R | Document height in current ruler units |410| `resolution` | number | R | DPI (pixels per inch) |411| `name` | string | **R/W** | **Photopea extension** — display label (no history step) |412| `source` | string | **R/W** | **Photopea extension** — file origin URL or `"local,X,NAME"` |413| `mode` | DocumentMode | R | `DocumentMode.RGB`, `GRAYSCALE`, `CMYK`, `LAB`, `BITMAP`, `INDEXEDCOLOR`, `MULTICHANNEL` |414| `bitsPerChannel` | BitsPerChannelType | R | `BitsPerChannelType.EIGHT`, `SIXTEEN`, `THIRTYTWO` |415| `colorProfileName` | string | R | Name of embedded color profile |416| `activeLayer` | Layer/ArtLayer/LayerSet | R/W | Set to activate a layer |417| `currentLayer` | ArtLayer | R/W | Alias for `activeLayer` |418| `layers` | Layers | R | All top-level layers (both art + group) |419| `artLayers` | ArtLayers | R | All top-level art layers only |420| `layerSets` | LayerSets | R | All top-level group layers only |421| `selection` | Selection | R | The current selection |422| `channels` | Channels | R | All channels |423| `historyStates` | HistoryStates | R | Undo history |424| `activeHistoryState` | HistoryState | R/W | Current history position |425| `layerComps` | LayerComps | R | Layer comps collection |426| `guides` | Guides | R | Guides collection |427| `pathItems` | PathItems | R | Vector paths |428| `id` | number | R | Unique document ID |429| `saved` | boolean | R | Whether document has unsaved changes |430| `quickMaskMode` | boolean | R | Whether in Quick Mask mode |431| `backgroundLayer` | ArtLayer | R | The background layer |432| `pixelAspectRatio` | number | R | Custom pixel aspect ratio (0.1–10.0) |433| `histogram` | array | R | 256-element histogram array |434435### Methods436437| Method | Signature | Description |438|--------|-----------|-------------|439| `resizeImage` | `(w, h, res, resampleMethod)` | Resize image pixels. ResampleMethod: `BICUBIC`, `BILINEAR`, `NEARESTNEIGHBOR`, `NONE`, `BICUBICSHARPER`, `BICUBICSMOOTHER` |440| `resizeCanvas` | `(w, h, anchor)` | Resize canvas without scaling. AnchorPosition: `TOPLEFT`, `TOPCENTER`, `TOPRIGHT`, `MIDDLELEFT`, `MIDDLECENTER`, `MIDDLERIGHT`, `BOTTOMLEFT`, `BOTTOMCENTER`, `BOTTOMRIGHT` |441| `rotateCanvas` | `(degrees)` | Rotate entire canvas. Positive = clockwise |442| `flipCanvas` | `(direction)` | `Direction.HORIZONTAL` or `Direction.VERTICAL` |443| `crop` | `([x1,y1,x2,y2], angle, w, h)` | Crop canvas. Angle and dimensions are optional |444| `trim` | `(trimType, top, left, bottom, right)` | Trim transparent/background-color borders. TrimType: `TRANSPARENT`, `TOPLEFT`, `BOTTOMRIGHT` |445| `revealAll` | `()` | Expand canvas to show clipped content |446| `flatten` | `()` | Merge all layers into one |447| `mergeVisibleLayers` | `()` | Merge all visible layers |448| `rasterizeAllLayers` | `()` | Rasterize all vector/text layers |449| `changeMode` | `(mode, options)` | Convert color mode (e.g., `ChangeMode.GRAYSCALE`) |450| `convertProfile` | `(profileName, renderingIntent, blackPointCompensation, dither)` | Convert color profile |451| `duplicate` | `(name, mergedLayers)` | Duplicate the document |452| `close` | `(saveOptions)` | Close document. SaveOptions: `DONOTSAVECHANGES`, `SAVECHANGES`, `PROMPTTOSAVECHANGES` |453| `save` | `()` | Save (requires server config in embed) |454| `saveToOE` | `(format)` | **Photopea extension** — send binary to host. Formats: `"png"`, `"jpg:0.8"`, `"webp:0.7"`, `"psd:true"`, `"svg:true"` |455| `clearHistory` | `()` | **Photopea extension** — clear undo history to free RAM |456| `exportDocument` | `(file, exportType, options)` | Export to filesystem (triggers ZIP). ExportType: `SAVEFORWEB` |457| `paste` | `(intoSelection)` | Paste clipboard into document |458| `suspendHistory` | `(historyName, callback)` | Wrap multiple ops in one history state |459460**Practical examples:**461```js462var doc = app.activeDocument;463464// Resize image to 1920×1080 at 72dpi bicubic465doc.resizeImage(1920, 1080, 72, ResampleMethod.BICUBIC);466467// Expand canvas to 2000px wide, keeping content centered468doc.resizeCanvas(2000, doc.height, AnchorPosition.MIDDLECENTER);469470// Crop to a region471doc.crop([100, 100, 900, 600]);472473// Trim transparent edges474doc.trim(TrimType.TRANSPARENT, true, true, true, true);475476// Flip horizontal477doc.flipCanvas(Direction.HORIZONTAL);478479// Change to grayscale480doc.changeMode(ChangeMode.GRAYSCALE);481482// One undo step for many operations483doc.suspendHistory("Batch Edit", "action");484// (Inside Photopea, all ops become one history state)485486// Export PNG to filesystem (triggers ZIP download)487var opts = new ExportOptionsSaveForWeb();488opts.format = SaveDocumentType.PNG;489opts.PNG8 = false;490opts.quality = 100;491doc.exportDocument(new File("/output.png"), ExportType.SAVEFORWEB, opts);492493// Close without saving494doc.close(SaveOptions.DONOTSAVECHANGES);495```496497---498499## `Layers` / `ArtLayers` / `LayerSets` Collections500501These collections exist on `Document`, `LayerSet` (groups within groups), and can be iterated.502503```js504var doc = app.activeDocument;505506// Access507doc.layers // all top-level (art + groups)508doc.artLayers // top-level art layers only509doc.layerSets // top-level group layers only510511// By index (0 = topmost)512doc.layers[0]513doc.layers[doc.layers.length - 1] // bottommost514515// By name (throws if not found)516doc.layers.getByName("Background")517doc.artLayers.getByName("Logo")518doc.layerSets.getByName("Header Group")519520// Add521var newLayer = doc.artLayers.add(); // new blank art layer522var newGroup = doc.layerSets.add(); // new group523var innerLayer = newGroup.artLayers.add(); // layer inside a group524525// Remove526doc.artLayers.getByName("Temp").remove();527528// Iterate all layers recursively529function walkLayers(parent) {530 for (var i = 0; i < parent.layers.length; i++) {531 var l = parent.layers[i];532 if (l.typename === "LayerSet") walkLayers(l);533 else /* ArtLayer */ processLayer(l);534 }535}536walkLayers(doc);537```538539---540541## `ArtLayer` — Individual Layer542543### Properties544545| Property | Type | R/W | Description |546|----------|------|-----|-------------|547| `name` | string | R/W | Layer name |548| `visible` | boolean | R/W | Layer visibility |549| `opacity` | number | R/W | Layer opacity 0–100 |550| `fillOpacity` | number | R | Fill opacity 0–100 |551| `blendMode` | BlendMode | R/W | Blend mode (see enum below) |552| `kind` | LayerKind | R/W | Layer type (can set to `LayerKind.TEXT` on empty layer) |553| `textItem` | TextItem | R | Text object (only when `kind === LayerKind.TEXT`) |554| `bounds` | array | R | `[left, top, right, bottom]` in current ruler units |555| `parent` | Document/LayerSet | R | Containing object |556| `typename` | string | R | Always `"ArtLayer"` |557| `selected` | boolean | R | **Photopea extension** — is layer highlighted in panel |558| `isBackgroundLayer` | boolean | R | Is this the locked background layer |559| `grouped` | boolean | R | Is clipping mask applied |560| `pixelsLocked` | boolean | R | Pixels locked |561| `positionLocked` | boolean | R | Position locked |562| `transparentPixelsLocked` | boolean | R | Transparent pixels locked |563| `layerMaskDensity` | number | R | Layer mask density 0–100 |564| `layerMaskFeather` | number | R | Layer mask feather 0–250 |565| `vectorMaskDensity` | number | R | Vector mask density 0–100 |566| `vectorMaskFeather` | number | R | Vector mask feather 0–250 |567568### Transform Methods569570| Method | Signature | Description |571|--------|-----------|-------------|572| `translate` | `(deltaX, deltaY)` | Move layer by offset |573| `rotate` | `(angle, anchor)` | Rotate by degrees. AnchorPosition optional (default center) |574| `resize` | `(widthPct, heightPct, anchor)` | Scale as percentage of current size |575| `rasterize` | `(target)` | Rasterize. RasterizeType: `ENTIRE`, `FILLCONTENT`, `LAYERCLIPPINGMASK`, `LINKEDLAYERS`, `SHAPE`, `TEXTCONTENTS`, `VECTORMASK` |576577### Layer Management Methods578579| Method | Signature | Description |580|--------|-----------|-------------|581| `duplicate` | `()` | Duplicate to same document, returns new layer |582| `duplicate` | `(doc, placement)` | Duplicate to another document |583| `remove` | `()` | Delete the layer |584| `merge` | `()` | Merge down; returns the merged ArtLayer |585| `move` | `(relativeLayer, placement)` | Reorder. ElementPlacement: `PLACEBEFORE`, `PLACEAFTER`, `PLACEATBEGINNING`, `PLACEATEND`, `INSIDE` |586| `copy` | `(merged)` | Copy to clipboard |587| `cut` | `()` | Cut to clipboard |588| `clear` | `()` | Cut without clipboard |589590### Adjustment Methods on ArtLayer591592| Method | Signature | Description |593|--------|-----------|-------------|594| `adjustBrightnessContrast` | `(brightness, contrast)` | Brightness -100–100, Contrast -100–100 |595| `adjustColorBalance` | `(shadows, midtones, highlights, preserveLuminosity)` | Each is `[cyan-red, magenta-green, yellow-blue]` array |596| `adjustCurves` | `(curveShape)` | Array of `[input,output]` pairs per channel |597| `adjustLevels` | `(inputRangeStart, inputRangeEnd, gamma, outputRangeStart, outputRangeEnd)` | Levels adjustment |598| `autoLevels` | `()` | Auto levels |599| `autoContrast` | `()` | Auto contrast |600| `desaturate` | `()` | Convert to grayscale values in current mode |601| `equalize` | `()` | Equalize brightness distribution |602| `invert` | `()` | Invert pixel colors |603| `posterize` | `(levels)` | Posterize (2–255 levels) |604| `threshold` | `(level)` | B&W threshold (1–255) |605| `shadowHighlight` | `(shadowAmount, shadowWidth, shadowRadius, highlightAmount, highlightWidth, highlightRadius, colorCorrection, midtoneContrast, blackClip, whiteClip)` | Shadows/Highlights |606| `photoFilter` | `(fillColor, density, luminosity)` | Photo filter |607| `mixChannels` | `(outputChannels, monochrome)` | Channel mixer |608| `selectiveColor` | `(colors, cyan, magenta, yellow, black, method)` | Selective color |609610### Filter Methods on ArtLayer611612| Method | Signature | Description |613|--------|-----------|-------------|614| `applyGaussianBlur` | `(radius)` | Gaussian blur (0.1–250 px radius) |615| `applyMotionBlur` | `(angle, distance)` | Motion blur |616| `applyRadialBlur` | `(amount, blurMethod, blurQuality)` | Radial blur |617| `applySmartBlur` | `(radius, threshold, blurQuality, blurMode)` | Smart blur |618| `applyBlur` | `()` | Simple blur |619| `applyBlurMore` | `()` | Blur more |620| `applyUnSharpMask` | `(amount, radius, threshold)` | Unsharp mask |621| `applySharpen` | `()` | Sharpen |622| `applySharpenEdges` | `()` | Sharpen edges |623| `applySharpenMore` | `()` | Sharpen more |624| `applyAddNoise` | `(amount, distribution, monochromatic)` | Add noise. NoiseDistribution: `GAUSSIAN`, `UNIFORM` |625| `applyDespeckle` | `()` | Despeckle |626| `applyDustAndScratches` | `(radius, threshold)` | Dust and scratches |627| `applyMedianNoise` | `(radius)` | Median noise reduction |628| `applyMaximum` | `(radius)` | Maximum filter (dilate) |629| `applyMinimum` | `(radius)` | Minimum filter (erode) |630| `applyHighPass` | `(radius)` | High pass |631| `applyOffset` | `(horizontal, vertical, undefinedAreas)` | Offset. UndefinedAreas: `SETTOBACKGROUND`, `WRAPAROUND`, `REPEATEDGEPIXELS` |632| `applyRipple` | `(amount, size)` | Ripple. RippleSize: `SMALL`, `MEDIUM`, `LARGE` |633| `applyWave` | `(generators, minWavelength, maxWavelength, minAmplitude, maxAmplitude, horizScale, vertScale, waveType, undefinedAreas, randomSeed)` | Wave filter |634| `applyZigZag` | `(amount, ridges, style)` | Zig-Zag |635| `applyTwirl` | `(angle)` | Twirl |636| `applyPolarCoordinates` | `(conversion)` | Polar coordinates |637| `applySpherize` | `(amount, mode)` | Spherize |638| `applyPinch` | `(amount)` | Pinch (-100–100) |639| `applyShear` | `(curve, undefinedAreas)` | Shear |640| `applyDisplace` | `(horizontalScale, verticalScale, displacementType, undefinedAreas, displacementMapFile)` | Displace |641| `applyClouds` | `()` | Render Clouds |642| `applyDifferenceClouds` | `()` | Difference Clouds |643| `applyLensFlare` | `(brightness, flareCenter, lensType)` | Lens Flare. LensType: `ZOOMWIDE, ZOOMNORMAL, MOVIE` |644| `applyDiffuseGlow` | `(graininess, glowAmount, clearAmount)` | Diffuse Glow |645| `applyGlassEffect` | `(distortion, smoothness, scaling, invert, texture, textureFile)` | Glass |646| `applyOceanRipple` | `(size, magnitude)` | Ocean Ripple |647| `applyLensBlur` | `(source, focalDistance, invertDepthMap, shape, radius, bladeCurvature, rotation, brightness, threshold, amount, distribution, monochromatic)` | Lens Blur |648| `applyAverage` | `()` | Average blur |649| `applyDeInterlace` | `(eliminateFields, createFields)` | De-interlace |650| `applyNTSC` | `()` | NTSC colors |651| `applyCustomFilter` | `(characteristics, scale, offset)` | Custom filter (5×5 matrix) |652| `applyTextureFill` | `(textureFile)` | Texture fill |653| `applyStyle` | `(styleName)` | Apply a layer style preset by name |654| `photoFilter` | `(fillColor, density, luminosity)` | Photo Filter |655656**Practical examples:**657```js658var layer = app.activeDocument.activeLayer;659660// Move to absolute position (layer.bounds[0] = current left edge)661layer.translate(200 - layer.bounds[0], 100 - layer.bounds[1]);662663// Rotate 45° around center664layer.rotate(45);665666// Scale to 50% keeping center667layer.resize(50, 50, AnchorPosition.MIDDLECENTER);668669// Gaussian blur radius 10670layer.applyGaussianBlur(10);671672// Unsharp mask673layer.applyUnSharpMask(50, 2, 0);674675// Levels: input 0–200, gamma 1.2, output 0–255676layer.adjustLevels(0, 200, 1.2, 0, 255);677678// Brightness +20, Contrast +10679layer.adjustBrightnessContrast(20, 10);680681// Invert682layer.invert();683684// Rasterize text685layer.rasterize(RasterizeType.TEXTCONTENTS);686687// Duplicate layer688var copy = layer.duplicate();689copy.name = "Layer Copy";690691// Move layer below another692var target = doc.layers.getByName("Background");693layer.move(target, ElementPlacement.PLACEAFTER);694```695696---697698## `LayerSet` — Group Layer699700A LayerSet is a folder/group in the Layers panel. It has the same layer management methods as `Document`.701702### Properties703704| Property | Type | R/W | Description |705|----------|------|-----|-------------|706| `name` | string | R/W | Group name |707| `visible` | boolean | R/W | Group visibility |708| `opacity` | number | R/W | Group opacity 0–100 |709| `blendMode` | BlendMode | R/W | Group blend mode |710| `bounds` | array | R | Bounding box `[left,top,right,bottom]` |711| `layers` | Layers | R | All layers inside this group |712| `artLayers` | ArtLayers | R | Art layers inside this group |713| `layerSets` | LayerSets | R | Sub-groups inside this group |714| `parent` | Document/LayerSet | R | Parent container |715| `typename` | string | R | Always `"LayerSet"` |716717### Methods718Same as Document for layer management: `layers.add()`, `artLayers.add()`, `layerSets.add()`, `.getByName()`, plus `duplicate()`, `remove()`, `move()`.719720```js721// Create group with layers inside722var group = doc.layerSets.add();723group.name = "Product Card";724725var bgLayer = group.artLayers.add(); bgLayer.name = "Background";726var textLayer = group.artLayers.add(); textLayer.kind = LayerKind.TEXT;727textLayer.textItem.contents = "Buy Now";728textLayer.textItem.size = 36;729730// Collapse/expand group (Photopea specific, not in standard DOM)731// Use visibility as workaround732733// Get specific layer inside a group734var innerLayer = doc.layerSets.getByName("Header Group").artLayers.getByName("Title");735```736737---738739## `TextItem` — Text Layer Content740741Access via `layer.textItem` on any layer with `layer.kind === LayerKind.TEXT`.742743### Core Properties (most commonly used)744745| Property | Type | R/W | Description |746|----------|------|-----|-------------|747| `contents` | string | R/W | The actual text content |748| `font` | string | R/W | Font PostScript name (e.g. `"ArialMT"`, `"Verdana-Bold"`) |749| `size` | number | R/W | Font size in points |750| `color` | SolidColor | R/W | Text color |751| `position` | array | R/W | `[x, y]` origin of text (point text) or bounding box top-left |752| `justification` | Justification | R/W | `Justification.LEFT`, `CENTER`, `RIGHT`, `FULLJUSTIFY` |753| `kind` | TextType | R/W | `TextType.POINTTEXT` or `TextType.PARAGRAPHTEXT` |754| `width` | number | R/W | Width of bounding box (paragraph text only) |755| `height` | number | R/W | Height of bounding box (paragraph text only) |756| `direction` | Direction | R/W | `Direction.HORIZONTAL` or `Direction.VERTICAL` |757758### Typography Properties759760| Property | Type | R/W | Description |761|----------|------|-----|-------------|762| `leading` | number | R/W | Line spacing in points |763| `tracking` | number | R/W | Letter spacing -1000–10000 (1000 = 1 em) |764| `horizontalScale` | number | R/W | Horizontal scaling 0–1000% |765| `verticalScale` | number | R/W | Vertical scaling 0–1000% |766| `baselineShift` | number | R/W | Baseline offset in points |767| `capitalization` | Case | R/W | `Case.NORMAL`, `ALLCAPS`, `SMALLCAPS` |768| `fauxBold` | boolean | R/W | Simulated bold |769| `fauxItalic` | boolean | R/W | Simulated italic |770| `underline` | UnderlineType | R/W | `UnderlineType.NONE`, `UNDERLINELEFT`, `UNDERLINERIGHT` |771| `strikeThru` | StrikeThruType | R/W | `StrikeThruType.NONE`, `STRIKEBOX`, `STRIKEHEIGHT` |772| `antiAliasMethod` | AntiAlias | R/W | `AntiAlias.NONE`, `SHARP`, `CRISP`, `STRONG`, `SMOOTH` |773| `autoKerning` | AutoKernType | R/W | `AutoKernType.MANUAL`, `METRICS`, `OPTICAL` |774| `language` | Language | R/W | `Language.ENGLISH`, etc. |775| `ligatures` | boolean | R/W | Enable ligatures |776| `alternateLigatures` | boolean | R/W | Enable alternate ligatures |777| `oldStyle` | boolean | R/W | Old-style numerals |778| `noBreak` | boolean | R/W | Prevent line breaks in this text |779| `useAutoLeading` | boolean | R/W | Use font's built-in leading |780| `autoLeadingAmount` | number | R/W | Auto leading percentage 0.01–5000 |781| `hyphenation` | boolean | R/W | Enable hyphenation |782783### Paragraph Properties784785| Property | Type | R/W | Description |786|----------|------|-----|-------------|787| `leftIndent` | number | R/W | Left indent -1296–1296 |788| `rightIndent` | number | R/W | Right indent -1296–1296 |789| `firstLineIndent` | number | R/W | First line indent -1296–1296 |790| `spaceBefore` | number | R/W | Space before paragraph -1296–1296 |791| `spaceAfter` | number | R/W | Space after paragraph -1296–1296 |792| `hangingPuntuation` | boolean | R/W | Roman hanging punctuation |793| `textComposer` | TextComposer | R/W | `TextComposer.ADOBEEVERYLINE`, `ADOBESINGLELINE` |794795### Warp Properties796797| Property | Type | R/W | Description |798|----------|------|-----|-------------|799| `warpStyle` | WarpStyle | R/W | `WarpStyle.NONE`, `ARC`, `ARCH`, `BULGE`, `SHELLLOWER`, `SHELLUPPER`, `FLAG`, `WAVE`, `FISH`, `RISE`, `FISHEYE`, `INFLATE`, `SQUEEZE`, `TWIST` |800| `warpDirection` | Direction | R/W | `Direction.HORIZONTAL` or `Direction.VERTICAL` |801| `warpBend` | number | R/W | Warp bend -100–100 |802| `warpHorizontalDistortion` | number | R/W | Horizontal distortion -100–100 |803| `warpVerticalDistortion` | number | R/W | Vertical distortion -100–100 |804805### Photopea Extensions806807| Property | Type | Description |808|----------|------|-------------|809| `totalTextStyle` | string | JSON string with ALL style parameters of the text |810| `transform` | string | JSON array — the affine transform matrix of the text |811812### Methods813814| Method | Description |815|--------|-------------|816| `convertToShape()` | Convert text to a filled shape layer with text as clipping path |817| `createPath()` | Create work path from text outlines |818819**Practical examples:**820```js821var layer = doc.layers.getByName("Headline");822var text = layer.textItem;823824// Set content825text.contents = "Hello World";826827// Style828text.font = "Verdana-Bold";829text.size = 72;830text.color.rgb.hexValue = "FF0000"; // red831832// Position point text at (50, 100)833text.position = [50, 100];834835// Center align836text.justification = Justification.CENTER;837838// Paragraph text with bounding box839text.kind = TextType.PARAGRAPHTEXT;840text.width = new UnitValue("400 pixels");841text.height = new UnitValue("200 pixels");842843// Letter spacing844text.tracking = 100; // 10% spacing845846// Scale text horizontally to 80%847text.horizontalScale = 80;848849// Warp arc850text.warpStyle = WarpStyle.ARC;851text.warpBend = 30;852853// Read all text styles as JSON (Photopea extension)854var styles = JSON.parse(text.totalTextStyle);855app.echoToOE(JSON.stringify(styles));856```857858---859860## Creating a Text Layer from Scratch861862```js863app.preferences.rulerUnits = Units.PIXELS;864865var layer = doc.artLayers.add();866layer.kind = LayerKind.TEXT; // Convert blank layer to text867layer.name = "My Title";868869var text = layer.textItem;870text.contents = "Welcome";871text.font = "ArialMT";872text.size = 48;873text.justification = Justification.CENTER;874text.position = [doc.width / 2, 100];875876var color = new SolidColor();877color.rgb.red = 255;878color.rgb.green = 255;879color.rgb.blue = 255;880text.color = color;881```882883---884885## `SolidColor` — Color Object886887```js888// RGB (most common in Photopea)889var c = new SolidColor();890c.rgb.red = 255; // 0–255891c.rgb.green = 128;892c.rgb.blue = 0;893c.rgb.hexValue = "FF8000"; // Set via hex string (no #)894895// CMYK896var c2 = new SolidColor();897c2.cmyk.cyan = 0; // 0–100898c2.cmyk.magenta = 50;899c2.cmyk.yellow = 100;900c2.cmyk.black = 0;901902// Grayscale903var c3 = new SolidColor();904c3.gray.gray = 50; // 0–100905906// HSB907var c4 = new SolidColor();908c4.hsb.hue = 30; // 0–360909c4.hsb.saturation = 100; // 0–100910c4.hsb.brightness = 100; // 0–100911912// Lab913var c5 = new SolidColor();914c5.lab.l = 50; // 0–100915c5.lab.a = 20; // -128–127916c5.lab.b = 40; // -128–127917918// Set as foreground color919app.foregroundColor = c;920921// Use with selection fill922doc.selection.selectAll();923doc.selection.fill(c);924doc.selection.deselect();925```926927---928929## `Selection` — Selection Object930931Access via `doc.selection`.932933### Properties934935| Property | Type | Description |936|----------|------|-------------|937| `bounds` | array | `[left, top, right, bottom]` bounding rectangle |938| `solid` | boolean | Whether selection is a solid rectangle |939940### Methods941942| Method | Signature | Description |943|--------|-----------|-------------|944| `selectAll` | `()` | Select entire document |945| `deselect` | `()` | Remove selection |946| `invert` | `()` | Invert the selection |947| `select` | `(region, type, feather, antiAlias)` | Select polygon region. Region is array of `[x,y]` points. SelectionType: `REPLACE`, `ADD`, `SUBTRACT`, `INTERSECT` |948| `feather` | `(radius)` | Feather the selection edges |949| `contract` | `(radius)` | Contract (shrink) selection |950| `expand` | `(radius)` | Expand selection |951| `grow` | `(tolerance, antiAlias)` | Grow selection to similar adjacent pixels |952| `similar` | `(tolerance, antiAlias)` | Select similar pixels throughout document |953| `smooth` | `(radius)` | Smooth selection edges |954| `selectBorder` | `(width)` | Select only the border of the current selection |955| `resize` | `(widthPct, heightPct, anchor)` | Resize selection boundary |956| `rotate` | `(angle, anchor)` | Rotate selection boundary |957| `translate` | `(deltaX, deltaY)` | Move selection boundary |958| `fill` | `(fillWith, mode, opacity, preserveTransparency)` | Fill selection with color or content. fillWith is SolidColor or string |959| `stroke` | `(strokeColor, width, location, mode, opacity, preserveTransparency)` | Stroke selection border. StrokeLocation: `INSIDE`, `OUTSIDE`, `CENTER` |960| `copy` | `(merged)` | Copy selection to clipboard |961| `cut` | `()` | Cut selection to clipboard |962| `clear` | `()` | Delete selection content |963| `load` | `(from, type, invert)` | Load selection from channel |964| `store` | `(into, type)` | Save selection as channel |965| `makeWorkPath` | `(tolerance)` | Convert to work path |966967**Practical examples:**968```js969var sel = doc.selection;970971// Rectangle select (top-left to bottom-right)972sel.select([[0,0],[500,0],[500,300],[0,300]]);973974// Select all975sel.selectAll();976977// Add to existing selection978sel.select([[600,0],[900,0],[900,300],[600,300]], SelectionType.ADD);979980// Feather 10px981sel.feather(10);982983// Contract by 5px984sel.contract(5);985986// Fill with red987var red = new SolidColor();988red.rgb.red = 255; red.rgb.green = 0; red.rgb.blue = 0;989sel.fill(red);990991// Stroke selection with black, 3px, inside992var black = new SolidColor();993black.rgb.hexValue = "000000";994sel.stroke(black, 3, StrokeLocation.INSIDE);995996// Copy, paste as new layer997sel.copy();998doc.paste();9991000// Invert and delete (remove background)1001sel.invert();1002sel.clear();1003sel.deselect();1004```10051006---10071008## `BlendMode` Enum — All Values10091010Used in `layer.blendMode` (string form in Photopea) and `BlendMode` constant (standard):10111012| `BlendMode` Constant | Photopea String | Name |1013|----------------------|-----------------|------|1014| `BlendMode.NORMAL` | `"norm"` | Normal |1015| `BlendMode.DISSOLVE` | `"diss"` | Dissolve |1016| `BlendMode.DARKEN` | `"dark"` | Darken |1017| `BlendMode.MULTIPLY` | `"mul "` | Multiply |1018| `BlendMode.COLORBURN` | `"idiv"` | Color Burn |1019| `BlendMode.LINEARBURN` | `"lbrn"` | Linear Burn |1020| `BlendMode.DARKERCOLOR` | `"dkCl"` | Darker Color |1021| `BlendMode.LIGHTEN` | `"lite"` | Lighten |1022| `BlendMode.SCREEN` | `"scrn"` | Screen |1023| `BlendMode.COLORDODGE` | `"div "` | Color Dodge |1024| `BlendMode.LINEARDODGE` | `"lddg"` | Linear Dodge (Add) |1025| `BlendMode.LIGHTERCOLOR` | `"lgCl"` | Lighter Color |1026| `BlendMode.OVERLAY` | `"over"` | Overlay |1027| `BlendMode.SOFTLIGHT` | `"sLit"` | Soft Light |1028| `BlendMode.HARDLIGHT` | `"hLit"` | Hard Light |1029| `BlendMode.VIVIDLIGHT` | `"vLit"` | Vivid Light |1030| `BlendMode.LINEARLIGHT` | `"lLit"` | Linear Light |1031| `BlendMode.PINLIGHT` | `"pLit"` | Pin Light |1032| `BlendMode.HARDMIX` | `"hMix"` | Hard Mix |1033| `BlendMode.DIFFERENCE` | `"diff"` | Difference |1034| `BlendMode.EXCLUSION` | `"smud"` | Exclusion |1035| `BlendMode.SUBTRACT` | `"fsub"` | Subtract |1036| `BlendMode.DIVIDE` | `"fdiv"` | Divide |1037| `BlendMode.HUE` | `"hue "` | Hue |1038| `BlendMode.SATURATION` | `"sat "` | Saturation |1039| `BlendMode.COLOR` | `"colr"` | Color |1040| `BlendMode.LUMINOSITY` | `"lum "` | Luminosity |1041| `BlendMode.PASSTHROUGH` | `"pass"` | Pass Through (groups only) |10421043```js1044// Use either form:1045layer.blendMode = BlendMode.SCREEN; // constant1046layer.blendMode = "scrn"; // string (Photopea internal form)1047```10481049---10501051## `LayerKind` Enum10521053| Constant | Description |1054|----------|-------------|1055| `LayerKind.NORMAL` | Regular pixel layer |1056| `LayerKind.TEXT` | Text layer |1057| `LayerKind.SMARTOBJECT` | Smart Object / linked layer |1058| `LayerKind.SOLIDFILL` | Solid color fill layer |1059| `LayerKind.GRADIENTFILL` | Gradient fill layer |1060| `LayerKind.PATTERNFILL` | Pattern fill layer |1061| `LayerKind.BRIGHTNESSCONTRAST` | Brightness/Contrast adjustment layer |1062| `LayerKind.CURVES` | Curves adjustment layer |1063| `LayerKind.LEVELS` | Levels adjustment layer |1064| `LayerKind.HUESATURATION` | Hue/Saturation adjustment layer |1065| `LayerKind.COLORBALANCE` | Color Balance adjustment layer |1066| `LayerKind.CHANNELMIXER` | Channel Mixer adjustment layer |1067| `LayerKind.GRADIENTMAP` | Gradient Map adjustment layer |1068| `LayerKind.INVERSION` | Invert adjustment layer |1069| `LayerKind.POSTERIZE` | Posterize adjustment layer |1070| `LayerKind.THRESHOLD` | Threshold adjustment layer |1071| `LayerKind.SELECTIVECOLOR` | Selective Color adjustment layer |1072| `LayerKind.PHOTOFILTER` | Photo Filter adjustment layer |1073| `LayerKind.EXPOSURE` | Exposure adjustment layer |1074| `LayerKind.VIBRANCE` | Vibrance adjustment layer |1075| `LayerKind.COLORLOOKUP` | Color Lookup adjustment layer |1076| `LayerKind.LAYER3D` | 3D layer (not generally useful in Photopea) |1077| `LayerKind.VIDEO` | Video layer |10781079```js1080// Identify layer type1081var layer = doc.activeLayer;1082if (layer.kind === LayerKind.TEXT) /* text layer */;1083if (layer.kind === LayerKind.SMARTOBJECT) /* smart object */;1084if (layer.typename === "LayerSet") /* group */;10851086// Filter: collect all text layers recursively1087var textLayers = [];1088function collectText(parent) {1089 for (var i = 0; i < parent.layers.length; i++) {1090 var l = parent.layers[i];1091 if (l.typename === "LayerSet") collectText(l);1092 else if (l.kind === LayerKind.TEXT) textLayers.push(l);1093 }1094}1095collectText(doc);1096```10971098---10991100## `AnchorPosition` Enum11011102| Constant | Position |1103|----------|----------|1104| `AnchorPosition.TOPLEFT` | Top left |1105| `AnchorPosition.TOPCENTER` | Top center |1106| `AnchorPosition.TOPRIGHT` | Top right |1107| `AnchorPosition.MIDDLELEFT` | Middle left |1108| `AnchorPosition.MIDDLECENTER` | Center |1109| `AnchorPosition.MIDDLERIGHT` | Middle right |1110| `AnchorPosition.BOTTOMLEFT` | Bottom left |1111| `AnchorPosition.BOTTOMCENTER` | Bottom center |1112| `AnchorPosition.BOTTOMRIGHT` | Bottom right |11131114---11151116## `ElementPlacement` Enum11171118Used with `layer.move(relativeObject, placement)`:11191120| Constant | Effect |1121|----------|--------|1122| `ElementPlacement.PLACEBEFORE` | Above the target layer in the panel |1123| `ElementPlacement.PLACEAFTER` | Below the target layer in the panel |1124| `ElementPlacement.PLACEATBEGINNING` | Top of the layer stack |1125| `ElementPlacement.PLACEATEND` | Bottom of the layer stack |1126| `ElementPlacement.INSIDE` | Into a LayerSet (makes layer a child) |11271128---11291130## `ResampleMethod` Enum11311132Used with `doc.resizeImage()`:11331134| Constant | Description |1135|----------|-------------|1136| `ResampleMethod.BICUBIC` | High quality, good for smooth gradients |1137| `ResampleMethod.BICUBICSHARPER` | Best for reduction |1138| `ResampleMethod.BICUBICSMOOTHER` | Best for enlargement |1139| `ResampleMethod.BILINEAR` | Medium quality |1140| `ResampleMethod.NEARESTNEIGHBOR` | No anti-aliasing, fastest |1141| `ResampleMethod.NONE` | No resampling (change resolution only) |11421143---11441145## `SaveOptions` Enum11461147Used with `doc.close(saveOption)`:11481149| Constant | Meaning |1150|----------|---------|1151| `SaveOptions.DONOTSAVECHANGES` | Discard all changes and close |1152| `SaveOptions.SAVECHANGES` | Save then close |1153| `SaveOptions.PROMPTTOSAVECHANGES` | Show dialog (may block in headless) |11541155---11561157## `ExportOptionsSaveForWeb` — Export to Filesystem11581159Used with `doc.exportDocument()` to write files that Photopea packages into a ZIP.11601161```js1162// Export PNG1163var pngOpts = new ExportOptionsSaveForWeb();1164pngOpts.format = SaveDocumentType.PNG;1165pngOpts.PNG8 = false; // PNG-241166pngOpts.quality = 100;1167pngOpts.transparency = true;1168doc.exportDocument(new File("/export.png"), ExportType.SAVEFORWEB, pngOpts);11691170// Export JPEG1171var jpgOpts = new ExportOptionsSaveForWeb();1172jpgOpts.format = SaveDocumentType.JPEG;1173jpgOpts.quality = 80; // 0–1001174doc.exportDocument(new File("/export.jpg"), ExportType.SAVEFORWEB, jpgOpts);11751176// Export GIF1177var gifOpts = new ExportOptionsSaveForWeb();1178gifOpts.format = SaveDocumentType.GIF;1179gifOpts.colors = 256;1180gifOpts.dither = 100;1181gifOpts.transparency = true;1182doc.exportDocument(new File("/export.gif"), ExportType.SAVEFORWEB, gifOpts);1183```11841185---11861187## `executeAction` — Advanced Operations11881189Used for operations not exposed in the standard DOM (adjustments applied as adjustment layers,1190Smart Object editing, etc.). Takes the Photoshop Action Manager approach.11911192```js1193// Open Smart Object for editing1194var l = doc.layers.getByName("SmartObj");1195doc.activeLayer = l;1196executeAction(stringIDToTypeID("placedLayerEditContents"));1197// Smart Object is now the active document1198doc.activeLayer.rotate(90);1199doc.save();1200doc.close();12011202// Apply Hue/Saturation as destructive adjustment1203var desc = new ActionDescriptor();1204var list = new ActionList();1205var channel = new ActionDescriptor();1206channel.putEnumerated(stringIDToTypeID("presetKind"), stringIDToTypeID("presetKindType"), stringIDToTypeID("presetKindDefault"));1207channel.putInteger(stringIDToTypeID("hue"), 20); // hue shift1208channel.putInteger(stringIDToTypeID("saturation"), 30); // saturation1209channel.putInteger(stringIDToTypeID("lightness"), 0);1210list.putObject(stringIDToTypeID("hueSaturationAdjustmentV2Layer"), channel);1211desc.putList(stringIDToTypeID("adjustment"), list);1212executeAction(stringIDToTypeID("hueSaturation"), desc, DialogModes.NO);12131214// Select a layer by name using AM1215function selectLayerByName(name) {1216 var desc = new ActionDescriptor();1217 var ref = new ActionReference();1218 ref.putName(charIDToTypeID("Lyr "), name);1219 desc.putReference(charIDToTypeID("null"), ref);1220 desc.putBoolean(charIDToTypeID("MkVs"), false);1221 executeAction(charIDToTypeID("slct"), desc, DialogModes.NO);1222}1223```12241225---12261227## Complete Practical Script Examples12281229### 1. Rename all text layers based on their contents1230```js1231app.preferences.rulerUnits = Units.PIXELS;1232var doc = app.activeDocument;12331234function processLayers(parent) {1235 for (var i = 0; i < parent.layers.length; i++) {1236 var l = parent.layers[i];1237 if (l.typename === "LayerSet") processLayers(l);1238 else if (l.kind === LayerKind.TEXT) {1239 l.name = l.textItem.contents.substring(0, 30);1240 }1241 }1242}1243processLayers(doc);1244app.echoToOE("done");1245```12461247### 2. Export each layer as a separate PNG1248```js1249app.preferences.rulerUnits = Units.PIXELS;1250var doc = app.activeDocument;12511252for (var i = 0; i < doc.layers.length; i++) {1253 // Hide all layers1254 for (var j = 0; j < doc.layers.length; j++) doc.layers[j].visible = false;1255 // Show only this layer1256 doc.layers[i].visible = true;1257 // Export1258 var opts = new ExportOptionsSaveForWeb();1259 opts.format = SaveDocumentType.PNG;1260 opts.PNG8 = false;1261 opts.quality = 100;1262 doc.exportDocument(1263 new File("/" + doc.layers[i].name + ".png"),1264 ExportType.SAVEFORWEB, opts1265 );1266}12671268// Restore visibility1269for (var i = 0; i < doc.layers.length; i++) doc.layers[i].visible = true;1270```12711272### 3. Find and replace text across all text layers1273```js1274var searchText = "2024";1275var replaceText = "2025";12761277function findReplaceText(parent) {1278 for (var i = 0; i < parent.layers.length; i++) {1279 var l = parent.layers[i];1280 if (l.typename === "LayerSet") findReplaceText(l);1281 else if (l.kind === LayerKind.TEXT) {1282 var t = l.textItem;1283 if (t.contents.indexOf(searchText) !== -1) {1284 t.contents = t.contents.split(searchText).join(replaceText);1285 }1286 }1287 }1288}1289findReplaceText(app.activeDocument);1290app.echoToOE("Find & Replace complete");1291```12921293### 4. Grid of duplicate layers1294```js1295app.preferences.rulerUnits = Units.PIXELS;1296var doc = app.activeDocument;1297var layer = doc.activeLayer;1298var cols = 4, rows = 3;1299var padX = 20, padY = 20;1300var w = layer.bounds[2] - layer.bounds[0];1301var h = layer.bounds[3] - layer.bounds[1];13021303for (var r = 0; r < rows; r++) {1304 for (var c = 0; c < cols; c++) {1305 if (r === 0 && c === 0) continue; // skip original1306 var copy = layer.duplicate();1307 var targetX = layer.bounds[0] + c * (w + padX);1308 var targetY = layer.bounds[1] + r * (h + padY);1309 copy.translate(targetX - copy.bounds[0], targetY - copy.bounds[1]);1310 copy.opacity = 100 - (r * cols + c) * 5;1311 }1312}1313```13141315### 5. Apply watermark from URL1316```js1317app.preferences.rulerUnits = Units.PIXELS;1318var doc = app.activeDocument;13191320// Open watermark as smart object layer1321app.open("https://example.com/watermark.png", null, true);1322var wm = doc.activeLayer;13231324// Resize to 20% of document width1325var wmW = wm.bounds[2] - wm.bounds[0];1326var targetW = doc.width * 0.2;1327var scalePct = (targetW / wmW) * 100;1328wm.resize(scalePct, scalePct, AnchorPosition.TOPLEFT);13291330// Move to bottom-right with 20px margin1331var wmNewW = wm.bounds[2] - wm.bounds[0];1332var wmNewH = wm.bounds[3] - wm.bounds[1];1333wm.translate(1334 doc.width - wmNewW - 20 - wm.bounds[0],1335 doc.height - wmNewH - 20 - wm.bounds[1]1336);1337wm.opacity = 60;1338app.echoToOE("watermark applied");1339```13401341### 6. Get all layer info as JSON1342```js1343function getLayerInfo(parent, depth) {1344 depth = depth || 0;1345 var result = [];1346 for (var i = 0; i < parent.layers.length; i++) {1347 var l = parent.layers[i];1348 var info = {1349 name: l.name,1350 type: l.typename,1351 visible: l.visible,1352 opacity: l.opacity,1353 depth: depth1354 };1355 if (l.typename === "ArtLayer") {1356 info.kind = l.kind.toString();1357 info.bounds = [l.bounds[0], l.bounds[1], l.bounds[2], l.bounds[3]];1358 if (l.kind === LayerKind.TEXT) {1359 info.text = l.textItem.contents;1360 info.font = l.textItem.font;1361 info.size = l.textItem.size;1362 }1363 } else if (l.typename === "LayerSet") {1364 info.children = getLayerInfo(l, depth + 1);1365 }1366 result.push(info);1367 }1368 return result;1369}1370app.echoToOE(JSON.stringify(getLayerInfo(app.activeDocument)));1371```13721373---13741375## Common Mistakes & Gotchas13761377| Problem | Cause | Fix |1378|---------|-------|-----|1379| `createEmbed` never resolves | Container has no size | Add `width` + `height` CSS to the container `<div>` |1380| `runScript` returns `["done"]` with no data | No `echoToOE` in script | Add `app.echoToOE(value)` for anything you want back |1381| `result[0]` is `"done"`, not the expected value | `echoToOE` not reached | Check script logic for early exit or errors |1382| Images won't load (network error) | CORS | Server must respond with `Access-Control-Allow-Origin: *` |1383| `openFromURL(url, true)` layer not ready | Async loading lag | Use `addImageAndWait` utility |1384| `exportImage` only PNG/JPG | `exportImage` limitation | Use `runScript("saveToOE('webp:0.85')")` for other formats |1385| Pixel coordinates behave unexpectedly | Wrong ruler units | Always set `app.preferences.rulerUnits = Units.PIXELS` first |1386| Text `size` set but looks different | Wrong type units | Set `app.preferences.typeUnits = TypeUnits.PIXELS` |1387| Layer not found by name | Wrong layer level | Layers are scoped; use recursive search for nested layers |1388| `layer.bounds[0]` returns a UnitValue, not number | Ruler units issue | Force `Units.PIXELS` before reading bounds |1389| Smart Object edit hangs | Missing `doc.save(); doc.close()` | Always save + close when done editing SO |1390| React double-mount in dev | Strict Mode | Use `if (peaRef.current) return` guard in `useEffect` |13911392---13931394## Limitations13951396- This skill covers host-page integration patterns; it does not replace Photopea's own terms, API documentation, or licensing guidance.1397- Remote URL loading depends on browser CORS behavior, network availability, and the user's Photopea account/session state.1398- `runScript` executes scripts inside the embedded Photopea document context. Only run scripts you understand and only with user-approved files.1399- Serialize dynamic values with `JSON.stringify` before embedding them in a `runScript` string. Never concatenate user-provided URLs, layer names, or text directly into Photopea script source.1400- Export behavior can vary by document size, browser memory limits, and the formats supported by the active Photopea runtime.14011402---14031404## Sources14051406- photopea.js: https://github.com/yikuansun/PhotopeaAPI1407- npm: https://www.npmjs.com/package/photopea1408- Photopea Live Messaging API: https://www.photopea.com/api/live1409- Photopea Script reference: https://www.photopea.com/learn/scripts1410- Photoshop JS Scripting reference (compatible): https://theiviaxx.github.io/photoshop-docs/Photoshop/index.html1411- Plugin dev gists (addImageAndWait, getDocumentAsImage): https://gist.github.com/yikuansun/c0f1a602b4e9d4e344a41c4f49ded3bf