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.activeDocument | Document | 읽기/쓰기 | 현재 활성 문서 |
app.documents | Documents | 읽기 | 열려 있는 모든 문서의 컬렉션 |
app.documents.length | number | 읽기 | 열려 있는 문서 수 |
app.documents[i] | Document | 읽기 | 0부터 시작하는 인덱스로 접근 |
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 확장 — 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]를 통해 접근합니다.
속성
| 속성 | 유형 | 읽기/쓰기 | 설명 |
|---|---|---|---|
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) | 자르기 |
…
[번역을 위해 잘림]