Communitygithub.com

JantonioFC/skillsbank

使用 photopea.js 在网页应用中嵌入 Photopea。涵盖嵌入、文件 I/O、脚本编写、导出、图层、文本、滤镜以及完整的兼容 Photoshop 的 API。

skillsbank 是什么?

该技能为 AI 助手提供了将 Photopea(一个基于 Web 的 Photoshop 替代品)无缝集成到网页应用中的能力。它围绕 `photopea.js` 库构建,该库是一个基于 Promise 的 JavaScript 封装,用于处理 Photopea 的实时消息 API。核心功能包括创建安全的 iframe 嵌入、通过 URL 或用户文件打开图像以及使用标准的 Adobe Photoshop JavaScript 脚本 API 运行任意脚本。开发者可以利用此技能自动化复杂的图像编辑工作流程,例如打开模板、操作文本和图层、应用滤镜以及以多种格式(PNG、JPEG、WebP、PSD)导出结果。这避免了使用低级 `postMessage` 直接通信的繁琐操作,提供了一种清晰的、基于 Promise 的方法来集成一个功能完整的图像编辑器,无需额外的基础设施。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/JantonioFC/skillsbank/tree/HEAD/plugins/antigravity-awesome-skills-claude/skills/photopea-embedded-editor

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

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.activeDocumentDocument读/写当前激活的文档
app.documentsDocuments只读所有打开文档的集合
app.documents.lengthnumber只读打开文档的数量
app.documents[i]Document只读按从零开始的索引访问
app.foregroundColorSolidColor读/写当前前景色
app.backgroundColorSolidColor读/写当前背景色
app.preferences.rulerUnitsUnits读/写Units.PIXELS、Units.CM、Units.INCHES、Units.MM、Units.PICAS、Units.POINTS、Units.PERCENT
app.preferences.typeUnitsTypeUnits读/写TypeUnits.PIXELS、TypeUnits.MM、TypeUnits.POINTS
app.displayDialogsDialogModes读/写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] 访问。

属性

属性类型读写描述
widthnumber只读文档宽度(以当前标尺单位计)
heightnumber只读文档高度(以当前标尺单位计)
resolutionnumber只读DPI(每英寸像素数)
namestring读/写Photopea 扩展 — 显示标签(无历史步骤)
sourcestring读/写Photopea 扩展 — 文件源 URL 或 "local,X,NAME"
modeDocumentMode只读DocumentMode.RGB、GRAYSCALE、CMYK、LAB、BITMAP、INDEXEDCOLOR、MULTICHANNEL
bitsPerChannelBitsPerChannelType只读BitsPerChannelType.EIGHT、SIXTEEN、THIRTYTWO
colorProfileNamestring只读嵌入的色彩配置文件名
activeLayerLayer/ArtLayer/LayerSet读/写设置为激活某个图层
currentLayerArtLayer读/写activeLayer 的别名
layersLayers只读所有顶层图层(包括艺术图层和组图层)
artLayersArtLayers只读仅所有顶层艺术图层
layerSetsLayerSets只读仅所有顶层组图层
selectionSelection只读当前选区
channelsChannels只读所有通道
historyStatesHistoryStates只读撤销历史
activeHistoryStateHistoryState读/写当前历史位置
layerCompsLayerComps只读图层复合集合
guidesGuides只读参考线集合
pathItemsPathItems只读矢量路径
idnumber只读文档唯一 ID
savedboolean只读文档是否有未保存的更改
quickMaskModeboolean只读是否处于快速蒙版模式
backgroundLayerArtLayer只读背景图层
pixelAspectRationumber只读自定义像素宽高比 (0.1–10.0)
histogramarray只读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)裁剪画布边缘的透明或彩色像素

...

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

JantonioFC/skillsbank

AI-powered image editing with style transfer and object removal

JantonioFC/skillsbank

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

JantonioFC/skillsbank

Analise e auditoria de editais de leilao judicial e extrajudicial. Riscos ocultos, clausulas perigosas, debitos, ocupante e classificacao da oportunidade.

JantonioFC/skillsbank

Best practices for Remotion - Video creation in React

JantonioFC/skillsbank

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

JantonioFC/skillsbank

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

JantonioFC/skillsbank

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

JantonioFC/skillsbank

Video and audio perception, indexing, and editing. Ingest files/URLs/live streams, build visual/spoken indexes, search with timestamps, edit timelines, add overlays/subtitles, generate media, and create real-time alerts.

JantonioFC/skillsbank

Upload, stream, search, edit, transcribe, and generate AI video and audio using the VideoDB SDK.

JantonioFC/skillsbank

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

JantonioFC/skillsbank

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

JantonioFC/skillsbank

Tool lifecycle UI components for React/Next.js from ui.inference.sh. Display tool calls: pending, progress, approval required, results. Capabilities: tool status, progress indicators, approval flows, results display. Use for: showing agent tool calls, human-in-the-loop approvals, tool output. Triggers: tool ui, tool calls, tool status, tool approval, tool results, agent tools, mcp tools ui, function calling ui, tool lifecycle, tool pending

JantonioFC/skillsbank

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

JantonioFC/skillsbank

When the user wants help with paid advertising campaigns on Google Ads, Meta (Facebook/Instagram), LinkedIn, Twitter/X, or other ad platforms. Also use when the user mentions 'PPC,' 'paid media,' 'ROAS,' 'CPA,' 'ad campaign,' 'retargeting,' 'audience targeting,' 'Google Ads,' 'Facebook ads,'...

JantonioFC/skillsbank

Create AI avatar and talking head videos with OmniHuman, Fabric, PixVerse via inference.sh CLI. Models: OmniHuman 1.5, OmniHuman 1.0, Fabric 1.0, PixVerse Lipsync. Capabilities: audio-driven avatars, lipsync videos, talking head generation, virtual presenters. Use for: AI presenters, expla...

JantonioFC/skillsbank

Create AI marketing videos for ads, promos, product launches, and brand content. Models: Veo, Seedance, Wan, FLUX for visuals, Kokoro for voiceover. Types: product demos, testimonials, explainers, social ads, brand videos. Use for: Facebook ads, YouTube ads, product launches, brand awarene...

JantonioFC/skillsbank

Generate AI videos with Google Veo, Seedance, Wan, Grok and 40+ models via inference.sh CLI. Models: Veo 3.1, Veo 3, Seedance 1.5 Pro, Wan 2.5, Grok Imagine Video, OmniHuman, Fabric, HunyuanVideo. Capabilities: text-to-video, image-to-video, lipsync, avatar animation, video upscaling, fole...

JantonioFC/skillsbank

Production-ready CI/CD configurations for Playwright — GitHub Actions, GitLab CI, CircleCI, Azure DevOps, Jenkins, Docker, parallel sharding, reporting, code coverage, and global setup/teardown.

JantonioFC/skillsbank

Next.js 16+ and Turbopack — incremental bundling, FS caching, dev speed, and when to use Turbopack vs webpack.

JantonioFC/skillsbank

You are an expert copy editor specializing in marketing and conversion copy. Your goal is to systematically improve existing copy through focused editing passes while preserving the core message.

相关技能