Photopea 嵌入式编辑器技能
在网站和应用程序中使用 photopea.js (yikuansun/PhotopeaAPI)
何时使用此技能
在每个涉及以下内容的任务中使用此技能:
- 将 Photopea 作为图像编辑器嵌入到网页或 Web 应用中
- 通过 JavaScript 代码控制嵌入的 Photopea 实例
- 从宿主页面自动化图像编辑工作流程(打开文件、运行脚本、导出结果)
- 使用 Photopea 作为引擎,在你的产品中构建图像编辑功能
- 编写脚本来操作文档、图层、文本、选区、滤镜、颜色和路径
不要使用原始的 postMessage 连接——始终使用 photopea.js 作为封装。
库: photopea.js
photopea.js 是一个基于 Promise 的 JavaScript 封装,围绕 Photopea Live Messaging API 构建。
仓库: https://github.com/yikuansun/PhotopeaAPI
npm 包: https://www.npmjs.com/package/photopea
安装
CDN(无需构建步骤)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/photopea.min.js"></script>
自托管
<script src="./photopea.min.js"></script>
npm(Webpack / Vite / Rollup)
npm install photopea
import Photopea from "photopea";
核心 API: Photopea 类
| 方法 | 描述 |
|---|---|
Photopea.createEmbed(container) | 创建并注入 iframe,就绪时解析 |
new Photopea(window.parent) | 插件模式:封装父窗口 |
pea.runScript(script) | 在 Photopea 内部运行 JS 字符串;返回输出数组 |
pea.loadAsset(arrayBuffer) | 加载二进制文件(图像、字体、画笔等) |
pea.openFromURL(url, asSmart) | 以新文档或智能对象图层形式打开远程 URL |
pea.exportImage(type) | 导出当前文档;返回 Blob("png" 或 "jpg") |
所有方法均返回 Promise——始终使用 await 或 .then()。
步骤 1 — 嵌入
容器 <div> 在调用 createEmbed 之前必须具有固定的宽度和高度。
<div id="editor" style="width:1000px; height:650px;"></div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/photopea.min.js"></script>
<script>
Photopea.createEmbed(document.getElementById("editor")).then(async (pea) => {
// pea 已就绪
});
</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" }} />;
}
步骤 2 — 打开文件
// 远程 URL → 新文档
await pea.openFromURL("https://example.com/design.psd", false);
// 远程 URL → 当前文档内的智能对象图层
await pea.openFromURL("https://example.com/overlay.png", true);
// 本地文件(用户输入 → ArrayBuffer → loadAsset)
document.getElementById("fileInput").addEventListener("change", async (e) => {
const buf = await e.target.files[0].arrayBuffer();
await pea.loadAsset(buf);
});
// 通过 runScript 使用 Base64 数据 URI
await pea.runScript(`app.open("data:image/png;base64,iVBORw0...");`);
步骤 3 — 运行脚本
runScript 发送一个 JS 字符串,返回一个包含所有 app.echoToOE(...) 值以及最后的 "done" 的数组。
const result = await pea.runScript(`app.echoToOE("hello");`);
// result → ["hello", "done"]
// 返回结构化数据
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]);
步骤 4 — 导出
// PNG Blob(通过 exportImage)
const blob = await pea.exportImage("png");
document.getElementById("preview").src = URL.createObjectURL(blob);
// JPEG Blob
const blob = await pea.exportImage("jpg");
// 通过 saveToOE 导出 WebP / PSD / 带质量参数的 JPEG
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" });
// 触发下载
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();
}
saveToOE 的导出格式字符串:
| 字符串 | 格式 |
|---|---|
"png" | PNG 无损 |
"jpg" | JPEG 默认 |
"jpg:0.8" | JPEG 质量 0.0–1.0 |
"webp:0.7" | WebP 质量 0.0–1.0 |
"psd" | 完整 PSD |
"psd:true" | 缩小版 PSD |
"svg:true" | SVG |
步骤 5 — 加载资源
// 字体
const buf = await (await fetch("https://example.com/MyFont.otf")).arrayBuffer();
await pea.loadAsset(buf);
// 现在可在 textItem.font 中使用
// 画笔
await pea.loadAsset(await (await fetch("Nature.ABR")).arrayBuffer());
// 渐变
await pea.loadAsset(await (await fetch("Gradients.GRD")).arrayBuffer());
步骤 6 — 插件模式
// 你的页面位于 Photopea 侧边栏 iframe 内
const pea = new Photopea(window.parent);
const out = await pea.runScript(`app.echoToOE(app.activeDocument.width);`);
console.log("宽度:", out[0]);
// 从你的插件加载资源
const buf = await (await fetch("https://my-assets.com/sticker.png")).arrayBuffer();
await pea.loadAsset(buf);
插件配置:
{
"environment": {
"plugins": [{
"name": "我的插件",
"url": "https://my-plugin.example.com",
"icon": "===https://my-plugin.example.com/icon.png"
}]
}
}
实用模式
addImageAndWait — 健壮的异步图层插入
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 — 返回 <img> 元素
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" }));
});
}
真实世界模式
模式 A — 打开 + 导出 UI
<input type="file" id="fileInput" accept="image/*,.psd">
<button id="exportBtn">导出 PNG</button>
<div id="editor" style="width:100%;height:600px;"></div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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>
模式 B — 模板 + 文本编辑 + 导出
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("名称").textItem.contents = ${nameLiteral};
app.activeDocument.layers.getByName("标语").textItem.contents = ${taglineLiteral};
`);
return await pea.exportImage("png");
}
模式 C — 批量水印
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;
}
完整脚本 API 参考
本节中的所有代码都在
pea.runScript("...")字符串内运行。 Photopea 实现了 Adobe Photoshop CC 2015 JavaScript 脚本接口。 任何针对该版本的 Photoshop 脚本都应在 Photopea 中正常工作。
app — 应用程序对象
属性
| 属性 | 类型 | 读写 | 描述 |
|---|---|---|---|
app.activeDocument | Document | 读/写 | 当前激活的文档 |
app.documents | Documents | 只读 | 所有打开文档的集合 |
app.documents.length | number | 只读 | 打开文档的数量 |
app.documents[i] | Document | 只读 | 按从零开始的索引访问 |
app.foregroundColor | SolidColor | 读/写 | 当前前景色 |
app.backgroundColor | SolidColor | 读/写 | 当前背景色 |
app.preferences.rulerUnits | Units | 读/写 | Units.PIXELS、Units.CM、Units.INCHES、Units.MM、Units.PICAS、Units.POINTS、Units.PERCENT |
app.preferences.typeUnits | TypeUnits | 读/写 | TypeUnits.PIXELS、TypeUnits.MM、TypeUnits.POINTS |
app.displayDialogs | DialogModes | 读/写 | DialogModes.NO、DialogModes.ALL、DialogModes.ERROR |
方法
| 方法 | 描述 |
|---|---|
app.open(url) | 以新文档形式打开 URL |
app.open(url, null, true) | 以当前文档中的智能对象图层形式打开 URL |
app.echoToOE(string) | Photopea 扩展 — 将字符串发送到宿主页面(由 runScript 捕获) |
app.showWindow("magiccut") | Photopea 扩展 — 打开魔术剪切面板 |
app.showWindow("vbitmap") | Photopea 扩展 — 打开位图矢量化面板 |
app.UI.zoomIn() | 放大 |
app.UI.zoomOut() | 缩小 |
app.UI.fitTheArea() | 将画布适配到视口 |
app.UI.pixelToPixel() | 100% 缩放 |
app.UI.switchFullscreen() | 切换全屏 |
app.UI.scroll(dx, dy) | 按增量滚动 |
app.UI.scrollTo(x, y) | 滚动到绝对位置 |
重要事项: 在任何使用像素测量的脚本开始时,务必将标尺单位设置为像素:
var savedUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// ... 你的代码 ...
app.preferences.rulerUnits = savedUnits;
Document — 文档对象
通过 app.activeDocument 或 app.documents[i] 访问。
属性
| 属性 | 类型 | 读写 | 描述 |
|---|---|---|---|
width | number | 只读 | 文档宽度(以当前标尺单位计) |
height | number | 只读 | 文档高度(以当前标尺单位计) |
resolution | number | 只读 | DPI(每英寸像素数) |
name | string | 读/写 | Photopea 扩展 — 显示标签(无历史步骤) |
source | string | 读/写 | Photopea 扩展 — 文件源 URL 或 "local,X,NAME" |
mode | DocumentMode | 只读 | DocumentMode.RGB、GRAYSCALE、CMYK、LAB、BITMAP、INDEXEDCOLOR、MULTICHANNEL |
bitsPerChannel | BitsPerChannelType | 只读 | BitsPerChannelType.EIGHT、SIXTEEN、THIRTYTWO |
colorProfileName | string | 只读 | 嵌入的色彩配置文件名 |
activeLayer | Layer/ArtLayer/LayerSet | 读/写 | 设置为激活某个图层 |
currentLayer | ArtLayer | 读/写 | activeLayer 的别名 |
layers | Layers | 只读 | 所有顶层图层(包括艺术图层和组图层) |
artLayers | ArtLayers | 只读 | 仅所有顶层艺术图层 |
layerSets | LayerSets | 只读 | 仅所有顶层组图层 |
selection | Selection | 只读 | 当前选区 |
channels | Channels | 只读 | 所有通道 |
historyStates | HistoryStates | 只读 | 撤销历史 |
activeHistoryState | HistoryState | 读/写 | 当前历史位置 |
layerComps | LayerComps | 只读 | 图层复合集合 |
guides | Guides | 只读 | 参考线集合 |
pathItems | PathItems | 只读 | 矢量路径 |
id | number | 只读 | 文档唯一 ID |
saved | boolean | 只读 | 文档是否有未保存的更改 |
quickMaskMode | boolean | 只读 | 是否处于快速蒙版模式 |
backgroundLayer | ArtLayer | 只读 | 背景图层 |
pixelAspectRatio | number | 只读 | 自定义像素宽高比 (0.1–10.0) |
histogram | array | 只读 | 256 元素直方图数组 |
方法
| 方法 | 签名 | 描述 |
|---|---|---|
resizeImage | (w, h, res, resampleMethod) | 调整图像像素。ResampleMethod: BICUBIC、BILINEAR、NEARESTNEIGHBOR、NONE、BICUBICSHARPER、BICUBICSMOOTHER |
resizeCanvas | (w, h, anchor) | 调整画布大小而不缩放。AnchorPosition: TOPLEFT、TOPCENTER、TOPRIGHT、MIDDLELEFT、MIDDLECENTER、MIDDLERIGHT、BOTTOMLEFT、BOTTOMCENTER、BOTTOMRIGHT |
rotateCanvas | (degrees) | 旋转整个画布。正数 = 顺时针 |
flipCanvas | (direction) | Direction.HORIZONTAL 或 Direction.VERTICAL |
crop | ([x1,y1,x2,y2], angle, w, h) | 裁剪画布。角度和尺寸可选 |
trim | (trimType, top, left, bottom, right) | 裁剪画布边缘的透明或彩色像素 |
...