Communitygithub.com

Photopea 임베디드 에디터 스킬

photopea.js를 사용하여 웹 앱에 Photopea를 임베딩하는 방법을 다룹니다. 임베딩, 파일 I/O, 스크립팅, 내보내기, 레이어, 텍스트, 필터 및 전체 Photoshop 호환 API를 포함합니다.

Photopea 임베디드 에디터 스킬란 무엇인가요?

이 스킬은 웹 애플리케이션에 Photopea 이미지 편집기를 임베딩하고 제어하는 방법을 상세히 설명합니다. `photopea.js` 라이브러리를 기반으로 하며, CDN, npm 또는 자체 호스팅 방식으로 설치할 수 있습니다. 핵심 API는 `Photopea` 클래스를 통해 제공되며, `createEmbed`로 iframe을 생성하고, `runScript`로 Photopea 내부에서 JavaScript를 실행하며, `loadAsset`으로 파일을 로드하고, `exportImage`로 결과물을 내보낼 수 있습니다. 또한 Adobe Photoshop CC 2015의 스크립팅 인터페이스를 완전히 지원하여 레이어 관리, 텍스트 편집, 필터 적용 등 고급 이미지 처리 작업을 자동화할 수 있습니다. 스킬은 React, 일반 HTML/JavaScript, 그리고 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에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Photopea 임베디드 에디터 스킬은(는) 무엇을 하나요?

웹사이트 및 앱에서 photopea.js (yikuansun/PhotopeaAPI) 사용하기


이 스킬을 사용해야 하는 경우

이 스킬은 다음과 같은 모든 작업에 사용하세요:

  • 웹페이지나 웹앱 내부에 이미지 편집기로 Photopea를 임베딩할 때
  • JavaScript 코드에서 임베디드 Photopea 인스턴스를 제어할 때
  • 호스트 페이지에서 이미지 편집 워크플로우를 자동화할 때 (파일 열기, 스크립트 실행, 결과 내보내기)
  • Photopea를 엔진으로 사용하여 제품에 이미지 편집 기능을 구축할 때
  • 문서, 레이어, 텍스트, 선택 영역, 필터, 색상 및 경로를 조작하는 스크립트를 작성할 때

하지 마세요 — 원시 postMessage 연결을 사용하지 말고, 항상 photopea.js를 래퍼로 사용하세요.


라이브러리: photopea.js

photopea.js는 Photopea Live Messaging API를 감싼 Promise 기반 JavaScript 래퍼입니다. 저장소: 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을 생성하고 주입하며, 준비되면 resolve합니다
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);
});

// Base64 데이터 URI (runScript 통해)
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");

// WebP / PSD / 품질 제어 JPEG (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" });

// 다운로드 트리거
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읽기0부터 시작하는 인덱스로 접근
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 확장 — Magic Cut 패널 열기
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.

관련 스킬