Communitygithub.com

Photopea Éditeur Intégré - compétence JantonioFC/skillsbank

Intégrez Photopea dans vos applications web avec photopea.js. Couvre l'intégration, la lecture/écriture de fichiers, le scripting, l'exportation, les calques, le texte, les filtres et l'API complète compatible Photoshop.

Qu'est-ce que skillsbank ?

Cette compétence permet aux agents d'IA et aux développeurs d'intégrer et de contrôler l'éditeur d'images Photopea directement dans une page web ou une application via la bibliothèque JavaScript `photopea.js`. Elle couvre l'ensemble du cycle de vie d'une tâche d'édition : l'intégration de l'iframe Photopea, l'ouverture de documents distants ou locaux, l'exécution de scripts JavaScript personnalisés pour manipuler les calques, le texte et les filtres, ainsi que l'exportation du résultat final. Cela évite d'utiliser des `postMessage` bruts et offre une interface Promises plus simple. Supportée par toutes les plateformes web (vanilla JS, React, Vue, etc.), cette compétence est utile pour construire des fonctionnalités d'édition avancées sans réinventer la roue. Elle s'appuie sur la documentation complète de l'API de scripting Photopea, compatible avec Adobe Photoshop CC 2015, permettant de réutiliser des scripts Photoshop existants.

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

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Compétence : Éditeur Photopea Intégré

Utilisation de photopea.js (yikuansun/PhotopeaAPI) dans les sites web et applications


Quand utiliser cette compétence

Utilisez cette compétence pour chaque tâche qui implique :

  • Intégrer Photopea en tant qu'éditeur d'images dans une page web ou une application web
  • Contrôler une instance Photopea intégrée depuis votre code JavaScript
  • Automatiser des workflows d'édition d'images à partir d'une page hôte (ouvrir des fichiers, exécuter des scripts, exporter les résultats)
  • Construire une fonctionnalité d'édition d'images dans votre produit en utilisant Photopea comme moteur
  • Écrire des scripts pour manipuler des documents, des calques, du texte, des sélections, des filtres, des couleurs et des chemins

N'utilisez PAS le postMessage brut — utilisez toujours photopea.js comme couche d'abstraction.


Bibliothèque : photopea.js

photopea.js est une surcouche JavaScript basée sur les Promesses autour de l'API de messagerie Photopea Live. Dépôt : https://github.com/yikuansun/PhotopeaAPI Paquet npm : https://www.npmjs.com/package/photopea

Installation

CDN (sans étape de build)

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/photopea.min.js"></script>

Hébergé localement

<script src="./photopea.min.js"></script>

npm (Webpack / Vite / Rollup)

npm install photopea
import Photopea from "photopea";

API principale : la classe Photopea

MéthodeDescription
Photopea.createEmbed(container)Crée et injecte l'iframe, résout quand il est prêt
new Photopea(window.parent)Mode plugin : enveloppe la fenêtre parente
pea.runScript(script)Exécute une chaîne JS à l'intérieur de Photopea ; retourne un tableau de sorties
pea.loadAsset(arrayBuffer)Charge un fichier binaire (image, police, pinceau, etc.)
pea.openFromURL(url, asSmart)Ouvre une URL distante en tant que nouveau document ou calque d'objet dynamique
pea.exportImage(type)Exporte le document actif ; retourne un Blob ("png" ou "jpg")

Toutes les méthodes retournent des Promesses — utilisez toujours await ou .then().


Étape 1 — Intégration

Le <div> conteneur doit avoir une largeur et une hauteur fixes avant d'appeler 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 est prêt
  });
</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" }} />;
}

Étape 2 — Ouverture de fichiers

// URL distante → nouveau document
await pea.openFromURL("https://example.com/design.psd", false);

// URL distante → calque d'objet dynamique dans le document actif
await pea.openFromURL("https://example.com/overlay.png", true);

// Fichier local (entrée utilisateur → ArrayBuffer → loadAsset)
document.getElementById("fileInput").addEventListener("change", async (e) => {
  const buf = await e.target.files[0].arrayBuffer();
  await pea.loadAsset(buf);
});

// URI de données Base64 via runScript
await pea.runScript(`app.open("data:image/png;base64,iVBORw0...");`);

Étape 3 — Exécution de scripts

runScript envoie une chaîne JS, retourne un tableau des valeurs app.echoToOE(...) + "done" en dernier.

const result = await pea.runScript(`app.echoToOE("hello");`);
// result → ["hello", "done"]

// Retourner des données structurées
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]);

Étape 4 — Exportation

// Blob PNG (via exportImage)
const blob = await pea.exportImage("png");
document.getElementById("preview").src = URL.createObjectURL(blob);

// Blob JPEG
const blob = await pea.exportImage("jpg");

// WebP / PSD / JPEG avec contrôle qualité via 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" });

// Déclencher le téléchargement
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();
}

Chaînes de format d'exportation pour saveToOE :

ChaîneFormat
"png"PNG sans perte
"jpg"JPEG par défaut
"jpg:0.8"JPEG qualité 0.0–1.0
"webp:0.7"WebP qualité 0.0–1.0
"psd"PSD complet
"psd:true"PSD minimisé
"svg:true"SVG

Étape 5 — Chargement d'actifs

// Police
const buf = await (await fetch("https://example.com/MyFont.otf")).arrayBuffer();
await pea.loadAsset(buf);
// Maintenant utilisable dans textItem.font

// Pinceau
await pea.loadAsset(await (await fetch("Nature.ABR")).arrayBuffer());

// Dégradé
await pea.loadAsset(await (await fetch("Gradients.GRD")).arrayBuffer());

Étape 6 — Mode Plugin

// Votre page est dans l'iframe de la barre latérale de Photopea
const pea = new Photopea(window.parent);

const out = await pea.runScript(`app.echoToOE(app.activeDocument.width);`);
console.log("Largeur :", out[0]);

// Charger un actif depuis votre plugin
const buf = await (await fetch("https://my-assets.com/sticker.png")).arrayBuffer();
await pea.loadAsset(buf);

Configuration du plugin :

{
  "environment": {
    "plugins": [{
      "name": "Mon Plugin",
      "url":  "https://mon-plugin.example.com",
      "icon": "===https://mon-plugin.example.com/icon.png"
    }]
  }
}

Modèles utilitaires

addImageAndWait — insertion robuste et asynchrone de calque

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 — retourne un élément <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" }));
  });
}

Exemples concrets

Exemple A — Interface Ouvrir + Exporter

<input type="file" id="fileInput" accept="image/*,.psd">
<button id="exportBtn">Exporter en 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>

Exemple B — Modèle + Édition de texte + Exportation

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");
}

Exemple C — Filigrane par lots

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;
}

RÉFÉRENCE COMPLÈTE DE L'API DE SCRIPTING

Tout le code de cette section s'exécute à l'intérieur de chaînes pea.runScript("..."). Photopea implémente l'interface de scripting JavaScript d'Adobe Photoshop CC 2015. Tout script Photoshop ciblant cette version devrait fonctionner dans Photopea.


app — Objet Application

Propriétés

PropriétéTypeL/EDescription
app.activeDocumentDocumentL/ELe document actuellement actif
app.documentsDocumentsLCollection de tous les documents ouverts
app.documents.lengthnumberLNombre de documents ouverts
app.documents[i]DocumentLAccès par index basé sur zéro
app.foregroundColorSolidColorL/ECouleur de premier plan actuelle
app.backgroundColorSolidColorL/ECouleur d'arrière-plan actuelle
app.preferences.rulerUnitsUnitsL/EUnits.PIXELS, Units.CM, Units.INCHES, Units.MM, Units.PICAS, Units.POINTS, Units.PERCENT
app.preferences.typeUnitsTypeUnitsL/ETypeUnits.PIXELS, TypeUnits.MM, TypeUnits.POINTS
app.displayDialogsDialogModesL/EDialogModes.NO, DialogModes.ALL, DialogModes.ERROR

Méthodes

MéthodeDescription
app.open(url)Ouvre une URL en tant que nouveau document
app.open(url, null, true)Ouvre une URL en tant que calque d'objet dynamique dans le document actif
app.echoToOE(string)Extension Photopea — envoie une chaîne à la page hôte (capturée par runScript)
app.showWindow("magiccut")Extension Photopea — ouvre le panneau Coupe magique
app.showWindow("vbitmap")Extension Photopea — ouvre le panneau Vectoriser le bitmap
app.UI.zoomIn()Zoom avant
app.UI.zoomOut()Zoom arrière
app.UI.fitTheArea()Ajuster le canevas à la zone d'affichage
app.UI.pixelToPixel()Zoom 100%
app.UI.switchFullscreen()Basculer en plein écran
app.UI.scroll(dx, dy)Faire défiler par delta
app.UI.scrollTo(x, y)Faire défiler vers une position absolue

Important : Définissez toujours les unités de règle en pixels au début de tout script qui utilise des mesures en pixels :

var savedUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// ... votre code ...
app.preferences.rulerUnits = savedUnits;

Document — Objet Document

Accès via app.activeDocument ou app.documents[i].

Propriétés

PropriétéTypeL/EDescription
widthnumberLLargeur du document dans les unités de règle actuelles
heightnumberLHauteur du document dans les unités de règle actuelles
resolutionnumberLDPI (pixels par pouce)
namestringL/EExtension Photopea — étiquette d'affichage (pas d'étape d'historique)
sourcestringL/EExtension Photopea — URL d'origine du fichier ou "local,X,NAME"
modeDocumentModeLDocumentMode.RGB, GRAYSCALE, CMYK, LAB, BITMAP, INDEXEDCOLOR, MULTICHANNEL
bitsPerChannelBitsPerChannelTypeLBitsPerChannelType.EIGHT, SIXTEEN, THIRTYTWO
colorProfileNamestringLNom du profil colorimétrique intégré
activeLayerLayer/ArtLayer/LayerSetL/EDéfinir pour activer un calque
currentLayerArtLayerL/EAlias pour activeLayer
layersLayersLTous les calques de premier niveau (art + groupe)
artLayersArtLayersLUniquement les calques d'art de premier niveau
layerSetsLayerSetsLUniquement les calques de groupe de premier niveau
selectionSelectionLLa sélection actuelle
channelsChannelsLTous les canaux
historyStatesHistoryStatesLHistorique des annulations
activeHistoryStateHistoryStateL/EPosition actuelle dans l'historique
layerCompsLayerCompsLCollection de compositions de calques
guidesGuidesLCollection de guides
pathItemsPathItemsLChemins vectoriels
idnumberLIdentifiant unique du document
savedbooleanLIndique si le document a des modifications non sauvegardées
quickMaskModebooleanLIndique si le mode Masque rapide est actif
backgroundLayerArtLayerLLe calque d'arrière-plan
pixelAspectRationumberLRatio d'aspect personnalisé des pixels (0.1–10.0)
histogramarrayLTableau d'histogramme de 256 éléments

Méthodes

MéthodeSignatureDescription
resizeImage(w, h, res, resampleMethod)Redimensionner les pixels de l'image. ResampleMethod : BICUBIC, BILINEAR, NEARESTNEIGHBOR, NONE, BICUBICSHARPER, BICUBICSMOOTHER
resizeCanvas(w, h, anchor)Redimensionner le canevas sans mise à l'échelle. AnchorPosition : TOPLEFT, TOPCENTER, TOPRIGHT, MIDDLELEFT, MIDDLECENTER, MIDDLERIGHT, BOTTOMLEFT, BOTTOMCENTER, BOTTOMRIGHT
rotateCanvas(degrees)Faire pivoter tout le canevas. Positif = horaire
flipCanvas(direction)Direction.HORIZONTAL ou Direction.VERTICAL
crop([x1,y1,x2,y2], angle, w, h)Rogner le canevas. L'angle et les dimensions sont optionnels
trim(trimType, top, left, bottom, right)Rogner les bords vides. TrimType : TrimType.TRANSPARENT, TrimType.TOPLEFT
close(SaveOptions)Fermer le document. SaveOptions : DONOTSAVECHANGES, SAVECHANGES, PROMPTTOSAVECHANGES
saveAs(saveIn, docName, asCopy, extensionType)Sauvegarder sous un nouveau fichier
duplicate(name, mergeLayersOnly)Dupliquer le document
flatten()Aplatir tous les calques
mergeVisibleLayers()Fusionner les calques visibles
mergeAllLayers()Fusionner tous les calques
link(layers)Lier un tableau de calques
suspendHistory(hint, script)Exécuter un script en tant qu'étape d'historique unique
runFilter(filterID)Exécuter un filtre par nom. Exemples : "SPHERIZE", "GLASS", "CROP", "AUTOCONTRAST", "COLORBALANCE"
rotateCanvasCustom(method)RotateMethod.BY180, CW90, CCW90, ARBITRARY

... (tronqué pour la traduction)

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.

Skills associés