Communitygithub.com

JantonioFC/skillsbank

在網頁應用程式中嵌入 Photopea 並使用 photopea.js 進行控制。涵蓋嵌入、檔案 I/O、腳本處理、匯出、圖層、文字、濾鏡以及完整的 Photoshop 相容 API。

skillsbank 是什麼?

此技能提供了一個基於 Promise 的 JavaScript 封裝層 (photopea.js),讓開發者能將 Photopea 嵌入網頁應用程式中,並透過 JavaScript 程式碼完全控制其運作。它專為需要建立線上影像編輯功能的產品而設計,支援從主頁面開啟檔案、執行腳本、匯出結果等工作流程,而無需手動處理低階的 postMessage 通訊。 該技能涵蓋了核心嵌入流程(createEmbed)、檔案載入(loadAsset、openFromURL)、腳本執行(runScript)、各種格式的匯出(exportImage、saveToOE)以及資產載入(字型、筆刷等)。此外,它也詳述了插件模式(Plugin Mode),讓在 Photopea 側邊欄 iframe 中執行的應用程式能與主 Photopea 實例互動。 技能中包含了實用的使用模式,例如非同步的圖層插入(addImageAndWait)、將文件轉換為<img>元素(getDocumentAsImage),以及真實世界的應用案例,如「開啟與匯出 UI」、「樣板文字編輯與匯出」和「批次加水印」。最後,它提供了完整的腳本 API 參考,涵蓋了 app(應用程式物件)、Document(文件物件)、Layer(圖層物件)以及其他許多 Photoshop 兼容的類別與方法,確保開發者能利用現有的 Photoshop 腳本知識來操控 Photopea。

相容平台~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 作為影像編輯器
  • 從您的 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,準備就緒時解析 Promise
new Photopea(window.parent)插件模式:封裝父視窗
pea.runScript(script)在 Photopea 內部執行 JavaScript 字串;回傳輸出陣列
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 發送一個 JavaScript 字串,回傳一個包含所有 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("Width:", out[0]);

// 從您的插件載入資產
const buf = await (await fetch("https://my-assets.com/sticker.png")).arrayBuffer();
await pea.loadAsset(buf);

插件設定檔:

{
  "environment": {
    "plugins": [{
      "name": "My Plugin",
      "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("Name").textItem.contents    = ${nameLiteral};
    app.activeDocument.layers.getByName("Tagline").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.length數字讀開啟文件的數量
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] 存取。

屬性

屬性類型讀/寫描述
width數字讀文件寬度(以當前標尺單位為準)
height數字讀文件高度(以當前標尺單位為準)
resolution數字讀DPI(每英寸像素數)
name字串讀/寫Photopea 擴充功能 — 顯示標籤(無歷史記錄步驟)
source字串讀/寫Photopea 擴充功能 — 檔案來源 URL 或 "local,X,NAME"
modeDocumentMode讀DocumentMode.RGB, GRAYSCALE, CMYK, LAB, BITMAP, INDEXEDCOLOR, MULTICHANNEL
bitsPerChannelBitsPerChannelType讀BitsPerChannelType.EIGHT, SIXTEEN, THIRTYTWO
colorProfileName字串讀嵌入的色彩描述檔名稱
activeLayerLayer/ArtLayer/LayerSet讀/寫設定以啟動一個圖層
currentLayerArtLayer讀/寫activeLayer 的別名
layersLayers讀所有頂層圖層(包括藝術圖層和圖層組)
artLayersArtLayers讀僅限所有頂層藝術圖層
layerSetsLayerSets讀僅限所有頂層圖層組
selectionSelection讀目前的選取範圍
channelsChannels讀所有色版
historyStatesHistoryStates讀復原歷史記錄
activeHistoryStateHistoryState讀/寫目前的歷史記錄位置
layerCompsLayerComps讀圖層複合集合
guidesGuides讀參考線集合
pathItemsPathItems讀向量路徑
id數字讀唯一的文件 ID
saved布林值讀文件是否有未儲存的變更
quickMaskMode布林值讀是否處於快速遮罩模式
backgroundLayerArtLayer讀背景圖層
pixelAspectRatio數字讀自訂像素長寬比 (0.1–10.0)
histogram陣列讀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.

相關技能