### Install photopea.js via CDN or npm Source: https://github.com/yikuansun/photopeaapi/blob/master/README.md Demonstrates how to include the photopea.js library in your project, either by linking to a CDN hosted version or by installing it using npm for module bundlers like Webpack, Rollup, or Vite. The npm installation also shows how to import the module. ```html ``` ```bash npm install photopea ``` ```javascript import Photopea from "photopea"; ``` -------------------------------- ### Photopea API Integration and Image Manipulation (JavaScript) Source: https://github.com/yikuansun/photopeaapi/blob/master/dist/test.html This snippet shows how to initialize the Photopea API, perform various image manipulations, and display the final output. It includes opening images from URLs, running scripts to modify layers (blend mode, translation), and exporting the image. Dependencies include the Photopea library and a container element in the HTML. ```javascript let container = document.getElementById("container"); Photopea.createEmbed(container).then(async (pea) => { let output = await pea.runScript(" app.echoToOE(\"hello world\"); "); console.log(output) await pea.openFromURL("https://www.photopea.com/api/img2/pug.png", false); await pea.runScript("app.activeDocument.activeLayer.blendMode = \"lddg\";"); await pea.openFromURL("https://www.photopea.com/api/img2/pug.png", true); await pea.runScript("app.activeDocument.activeLayer.blendMode = \"scrn\";"); await pea.runScript("app.activeDocument.activeLayer.translate(20, 20);"); output = await pea.runScript(" app.echoToOE(\"hello world 2\"); "); console.log(output) let finalImage = await pea.exportImage(); let img = new Image(); img.src = URL.createObjectURL(finalImage); document.body.appendChild(img); }); ``` -------------------------------- ### Export Image from Photopea Source: https://github.com/yikuansun/photopeaapi/blob/master/README.md Details the `exportImage` method for exporting the current document from Photopea. You can specify the image type (e.g., 'png', 'jpg'), and it returns a Blob object of the exported image. You can then use `URL.createObjectURL` to get a usable URL. ```javascript async exportImage(type="png") ``` -------------------------------- ### Initialize Photopea Instance Source: https://github.com/yikuansun/photopeaapi/blob/master/README.md Shows two ways to initialize a Photopea instance. The first is for plugins, using `window.parent` to interact with the existing Photopea instance. The second is for creating a new Photopea embed within a specified DOM container. ```javascript let pea = new Photopea(window.parent); Photopea.createEmbed(container).then(async (pea) => { // photopea initialized // pea is the new Photopea object // you can also use async/await: /* let pea = await Photopea.createEmbed(container); */ }); ``` -------------------------------- ### Create Photopea Plugin Instance Source: https://context7.com/yikuansun/photopeaapi/llms.txt Instantiates a Photopea object for use within a Photopea plugin to communicate with the parent window. ```APIDOC ## Create Photopea Plugin Instance ### Description Instantiates a Photopea object for use within a Photopea plugin to communicate with the parent window. ### Method `new Photopea(window.parent)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const pea = new Photopea(window.parent); await pea.runScript("app.echoToOE('Plugin loaded');"); ``` ### Response #### Success Response (200) - **pea** (Photopea) - The Photopea object for interacting with the parent window. #### Response Example ```json // Photopea object returned ``` ``` -------------------------------- ### Photopea Methods Source: https://github.com/yikuansun/photopeaapi/blob/master/README.md Asynchronous methods for interacting with an initialized Photopea instance. ```APIDOC ## Photopea Methods ### Description Methods available on a Photopea instance, all returning Promises. ### `runScript(script)` #### Description Executes a JavaScript script within Photopea. #### Method `async runScript(script)` #### Parameters - **script** (string) - Required - The JavaScript code to execute in Photopea. #### Request Example ```javascript let script = "app.openPanel('Layers');"; pea.runScript(script).then(result => { console.log('Script executed:', result); }); ``` #### Response ##### Success Response - **outputs** (Array) - An array containing the outputs of the executed script, ending with the string "done". ##### Response Example ```json ["Layer 1", "Layer 2", "done"] ``` ### `loadAsset(asset)` #### Description Loads an asset (e.g., image, PSD) into the current Photopea document. #### Method `async loadAsset(asset)` #### Parameters - **asset** (ArrayBuffer) - Required - A buffer containing the asset data. #### Request Example ```javascript fetch('path/to/your/image.psd') .then(response => response.arrayBuffer()) .then(buffer => { pea.loadAsset(buffer).then(() => console.log('Asset loaded')); }); ``` #### Response ##### Success Response - **status** (Array) - Typically returns `["done"]` upon successful loading. ##### Response Example ```json ["done"] ``` ### `openFromURL(url, asSmart)` #### Description Opens an image or PSD file directly from a URL. #### Method `async openFromURL(url, asSmart)` #### Parameters - **url** (string) - Required - The URL of the file to open. - **asSmart** (boolean) - Optional - Defaults to `true`. If `true`, opens as a smart object layer. If `false`, opens as a new document. #### Request Example ```javascript pea.openFromURL('https://example.com/image.jpg', false).then(() => console.log('Image opened')); ``` #### Response ##### Success Response - **status** (Array) - Typically returns `["done"]` upon successful opening. ##### Response Example ```json ["done"] ``` ### `exportImage(type)` #### Description Exports the current Photopea document as an image file. #### Method `async exportImage(type)` #### Parameters - **type** (string) - Optional - Defaults to `"png"`. The desired export file type (`"png"` or `"jpg"`). #### Request Example ```javascript pea.exportImage('jpg').then(blob => { const url = URL.createObjectURL(blob); console.log('Exported image URL:', url); }); ``` #### Response ##### Success Response - **blob** (Blob) - A Blob object representing the exported image file. ##### Response Example ```javascript // Returns a Blob object ``` ``` -------------------------------- ### Photopea Constructor Source: https://github.com/yikuansun/photopeaapi/blob/master/README.md Instantiate the Photopea class for interacting with Photopea. ```APIDOC ## Photopea Constructor ### Description Instantiates a Photopea object to interact with a Photopea instance. ### Method `new Photopea(contentWindow)` or `Photopea.createEmbed(container)` ### Parameters #### Constructor Parameters - **contentWindow** (Window) - Required - The window object of the Photopea instance (e.g., `window.parent` for plugins). - **container** (HTMLElement) - Required - The DOM element where the Photopea embed will be created. Should have defined width and height. ### Request Example ```javascript // For plugins let pea = new Photopea(window.parent); // To create a new embed Photopea.createEmbed(document.getElementById('photopea-container')).then(pea => { console.log('Photopea initialized'); }); ``` ### Response #### Success Response - **pea** (Photopea) - An instance of the Photopea class. ``` -------------------------------- ### Synchronous Execution with await Source: https://github.com/yikuansun/photopeaapi/wiki/Functions Demonstrates how to run asynchronous Photopea API calls synchronously by wrapping the code in an immediately invoked async function expression (IIAFE). This allows the use of `await` to pause execution until the asynchronous operation completes. ```javascript (async function() { alert(await Photopea.runScript(myframe.contentWindow, "app.echoToOE('Hello World!');")); })(); ``` -------------------------------- ### Open File from URL in Photopea Source: https://github.com/yikuansun/photopeaapi/blob/master/README.md Explains the `openFromURL` method, which allows opening an image or PSD file directly from a given URL. It includes an option `asSmart` to control whether the opened file becomes a smart layer. Returns `["done"]` on success. ```javascript async openFromURL(url, asSmart=true) ``` -------------------------------- ### Load Asset into Photopea Source: https://context7.com/yikuansun/photopeaapi/llms.txt Loads binary assets such as images, fonts, or brushes into Photopea. ```APIDOC ## Load Asset into Photopea ### Description Loads binary assets such as images, fonts, or brushes into Photopea. ### Method `pea.loadAsset(arrayBuffer)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **arrayBuffer** (ArrayBuffer) - Required - The binary data of the asset to load. ### Request Example ```javascript // Load an image file const fileInput = document.querySelector('input[type="file"]'); fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; if (file) { const arrayBuffer = await file.arrayBuffer(); await pea.loadAsset(arrayBuffer); console.log("Asset loaded"); } }); // Load a font from a URL const response = await fetch('https://example.com/fonts/custom-font.ttf'); const fontBuffer = await response.arrayBuffer(); await pea.loadAsset(fontBuffer); console.log("Font loaded successfully"); ``` ### Response #### Success Response (200) - **result** (Array) - Typically returns `["done"]` upon successful loading. #### Response Example ```json ["done"] ``` ``` -------------------------------- ### Create Photopea Plugin Instance Source: https://context7.com/yikuansun/photopeaapi/llms.txt Instantiates a Photopea object for use within a Photopea plugin. This allows communication between the plugin and the parent Photopea window. It takes the parent window object as an argument. ```javascript import Photopea from "photopea"; // For use inside a Photopea plugin const pea = new Photopea(window.parent); // Now you can interact with Photopea from your plugin await pea.runScript("app.echoToOE('Plugin loaded');"); ``` -------------------------------- ### Load Asset into Photopea Source: https://github.com/yikuansun/photopeaapi/blob/master/README.md Illustrates the `loadAsset` method, used to load binary data (ArrayBuffer) representing an asset into Photopea. This method returns a simple confirmation array `["done"]` upon successful loading. ```javascript async loadAsset(asset) ``` -------------------------------- ### Adding Binary Assets Source: https://github.com/yikuansun/photopeaapi/wiki/Functions Adds a binary asset, such as an image or font, to the Photopea process. Returns true upon successful addition. ```APIDOC ## addBinaryAsset ### Description Adds a binary asset (e.g., PSD, SVG, JPG, fonts, brushes) to the Photopea process running in the specified `contentWindow`. Returns `true`. ### Method `addBinaryAsset(contentWindow, asset)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **contentWindow** (Window) - Required - The `contentWindow` of the Photopea embed. For plugins, use `window.parent`. - **asset** (ArrayBuffer) - Required - The binary data of the asset to add. ### Request Example ```javascript // Assuming 'myEmbed' is the iframe element and 'imageArrayBuffer' is an ArrayBuffer of an image file fetch('/path/to/your/image.jpg') .then(response => response.arrayBuffer()) .then(arrayBuffer => { Photopea.addBinaryAsset(myEmbed.contentWindow, arrayBuffer).then((success) => { console.log('Asset added successfully:', success); }); }); ``` ### Response #### Success Response (200) - **success** (boolean) - `true` if the asset was added successfully. #### Response Example ```json true ``` ``` -------------------------------- ### Run a Script in Photopea Source: https://github.com/yikuansun/photopeaapi/blob/master/README.md Demonstrates the `runScript` method, which executes a given JavaScript script within the Photopea environment. It takes a script string as input and returns an array of outputs from the executed script, with the last element being 'done'. ```javascript async runScript(script) ``` -------------------------------- ### Running Scripts Source: https://github.com/yikuansun/photopeaapi/wiki/Functions Executes a given script within the Photopea process. It returns an array of data outputted by Photopea before 'done'. ```APIDOC ## runScript ### Description Runs a script within the Photopea process. Returns an array containing all data outputted by Photopea before 'done'. ### Method `runScript(contentWindow, script)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **contentWindow** (Window) - Required - The `contentWindow` of the Photopea embed. For plugins, use `window.parent`. - **script** (string) - Required - The JavaScript code to execute within Photopea. ### Request Example ```javascript // Assuming 'myEmbed' is the iframe element obtained from initEmbed Photopea.runScript(myEmbed.contentWindow, "app.echoToOE('Hello World!');").then((out_data) => { console.log(out_data[0]); // Logs 'Hello World!' }); ``` ### Response #### Success Response (200) - **out_data** (Array) - An array containing all data outputted by Photopea before 'done'. #### Response Example ```json ["Hello World!"] ``` ``` -------------------------------- ### Initialize Photopea Embed Source: https://github.com/yikuansun/photopeaapi/wiki/Functions Initializes an embeddable Photopea instance within a specified HTML element. The function returns a Promise that resolves with the iframe element once Photopea is ready. An optional configuration string can be provided to customize the embed. ```javascript Photopea.initEmbed(document.body).then((frame) => { ... }); ``` -------------------------------- ### Run Script in Photopea Source: https://github.com/yikuansun/photopeaapi/wiki/Functions Executes a given script within a running Photopea instance. The script is passed via the `script` argument, and the target Photopea instance is identified by its `contentWindow`. The function returns a Promise that resolves with an array of data outputted by Photopea before the 'done' keyword. For plugin contexts, `window.parent` should be used as the `contentWindow`. ```javascript Photopea.runScript(myEmbed.contentWindow, "app.echoToOE('Hello World!');").then((out_data) => console.log(out_data[0])); ``` -------------------------------- ### Create Photopea Embed with Configuration Source: https://context7.com/yikuansun/photopeaapi/llms.txt Creates an iframe with a Photopea instance, allowing for programmatic interaction. It accepts a container element and an optional configuration object for themes and UI elements. Returns a Photopea object for subsequent operations. ```javascript import Photopea from "photopea"; // Create a container div with dimensions const container = document.createElement("div"); container.style.width = "800px"; container.style.height = "600px"; document.body.appendChild(container); // Create embed with optional configuration const config = { theme: 1, // dark theme logo: 0 // hide logo }; try { const pea = await Photopea.createEmbed(container, config); console.log("Photopea initialized successfully"); // pea is now ready to use } catch (error) { console.error("Failed to initialize Photopea:", error); } ``` -------------------------------- ### Execute Photopea Script Source: https://context7.com/yikuansun/photopeaapi/llms.txt Runs a JavaScript script within the Photopea environment and returns the output. ```APIDOC ## Execute Photopea Script ### Description Runs a JavaScript script within the Photopea environment and returns the output. ### Method `pea.runScript(script)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **script** (string) - Required - The JavaScript code to execute within Photopea. ### Request Example ```javascript // Get document dimensions const result = await pea.runScript(` var doc = app.activeDocument; app.echoToOE(doc.width + "x" + doc.height); `); console.log("Document dimensions:", result[0]); // Create a new document await pea.runScript(` app.documents.add(800, 600, 72, "New Document", "rgb"); `); // Add text layer await pea.runScript(` var textLayer = app.activeDocument.artLayers.add(); textLayer.kind = "text"; textLayer.textItem.contents = "Hello, Photopea!"; textLayer.textItem.size = 48; app.echoToOE("Text layer added"); `); ``` ### Response #### Success Response (200) - **result** (Array) - An array containing the output from the executed script. The last element is typically 'done'. #### Response Example ```json // Example for getting dimensions: ["1920x1080", "done"] // Example for adding text layer: ["Text layer added", "done"] ``` ``` -------------------------------- ### Create Photopea Embed Source: https://context7.com/yikuansun/photopeaapi/llms.txt Creates an iframe containing a Photopea instance and returns a Photopea object for interacting with it. ```APIDOC ## Create Photopea Embed ### Description Creates an iframe containing a Photopea instance and returns a Photopea object for interacting with it. ### Method `createEmbed` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **container** (HTMLElement) - Required - The HTML element to append the Photopea iframe to. - **config** (Object) - Optional - Configuration object for the Photopea embed. - **theme** (number) - Optional - Theme for Photopea (e.g., 1 for dark theme). - **logo** (number) - Optional - Whether to show the logo (e.g., 0 to hide). ### Request Example ```javascript const container = document.createElement("div"); container.style.width = "800px"; container.style.height = "600px"; document.body.appendChild(container); const config = { theme: 1, // dark theme logo: 0 // hide logo }; const pea = await Photopea.createEmbed(container, config); console.log("Photopea initialized successfully"); ``` ### Response #### Success Response (200) - **pea** (Photopea) - The Photopea object for interacting with the embed. #### Response Example ```json // Photopea object returned ``` ``` -------------------------------- ### Embedding Photopea Source: https://github.com/yikuansun/photopeaapi/wiki/Functions Initializes a Photopea embed within a specified HTML element. It returns the created iframe element. ```APIDOC ## initEmbed ### Description Creates a Photopea embed in the specified HTML element. Returns the iframe element. ### Method `initEmbed(elem_to_append_to, [config])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **elem_to_append_to** (HTMLElement) - Required - The HTML element to append the Photopea embed to. - **config** (string) - Optional - A string representing the JSON configuration file for the embed. ### Request Example ```javascript Photopea.initEmbed(document.body, '{"theme":"dark"}').then((frame) => { console.log('Photopea embed created:', frame); }); ``` ### Response #### Success Response (200) - **frame** (HTMLIFrameElement) - The iframe element where Photopea is embedded. #### Response Example ```javascript // Returns an iframe element ``` ``` -------------------------------- ### Add Binary Asset to Photopea Source: https://github.com/yikuansun/photopeaapi/wiki/Functions Adds a binary asset, such as an image file (PSD, SVG, JPG) or a font, to a running Photopea instance. The asset must be provided as an ArrayBuffer. The function returns a Promise that resolves with `true` upon successful addition. Similar to `runScript`, for plugins, `window.parent` should be used for `contentWindow`. ```javascript Photopea.addBinaryAsset(myEmbed.contentWindow, asset); ``` -------------------------------- ### Load Assets into Photopea Source: https://context7.com/yikuansun/photopeaapi/llms.txt Loads binary assets like images, fonts, or brushes into the Photopea environment. This function accepts an ArrayBuffer representation of the asset. It can be used with files selected by a user or fetched from a URL. ```javascript // Load an image file as an asset const fileInput = document.querySelector('input[type="file"]'); fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; if (file) { try { const arrayBuffer = await file.arrayBuffer(); const result = await pea.loadAsset(arrayBuffer); console.log("Asset loaded:", result); // Output: ["done"] } catch (error) { console.error("Failed to load asset:", error); } } }); // Load a font from a URL try { const response = await fetch('https://example.com/fonts/custom-font.ttf'); const fontBuffer = await response.arrayBuffer(); await pea.loadAsset(fontBuffer); console.log("Font loaded successfully"); } catch (error) { console.error("Failed to load font:", error); } ``` -------------------------------- ### Execute Photopea Scripts for Document and Text Operations Source: https://context7.com/yikuansun/photopeaapi/llms.txt Runs JavaScript scripts within the Photopea environment to perform various actions. This includes retrieving document information, creating new documents, and adding text layers to the active document. The output of the script is returned. ```javascript // Execute a script to get document information try { const result = await pea.runScript(` var doc = app.activeDocument; app.echoToOE(doc.width + "x" + doc.height); `); console.log("Document dimensions:", result[0]); // Output: e.g., "1920x1080" console.log("Done status:", result[result.length - 1]); // Output: "done" } catch (error) { console.error("Script execution failed:", error); } // Create a new document with specific dimensions try { await pea.runScript(` app.documents.add(800, 600, 72, "New Document", "rgb"); `); console.log("New document created"); } catch (error) { console.error("Failed to create document:", error); } // Add text layer to active document try { const outputs = await pea.runScript(` var textLayer = app.activeDocument.artLayers.add(); textLayer.kind = "text"; textLayer.textItem.contents = "Hello, Photopea!"; textLayer.textItem.size = 48; app.echoToOE("Text layer added"); `); console.log(outputs[0]); // Output: "Text layer added" } catch (error) { console.error("Failed to add text layer:", error); } ``` -------------------------------- ### Open Image from URL in Photopea Source: https://context7.com/yikuansun/photopeaapi/llms.txt Opens an image from a specified URL into Photopea. It can either open the image as a new document or add it as a layer to the currently active document. This function is useful for automating image loading processes or creating composite images programmatically. Ensure the URL points to a valid image file. ```javascript // Open image as a new document try { await pea.openFromURL( 'https://i.imgur.com/example.png', false // false = open in new document ); console.log("Image opened in new document"); } catch (error) { console.error("Failed to open image:", error); } // Add image as a smart layer to current document try { await pea.openFromURL( 'https://i.imgur.com/logo.png', true // true = add as layer to active document ); console.log("Image added as layer"); } catch (error) { console.error("Failed to add image layer:", error); } // Complete workflow: open base image and add overlay async function createComposite() { try { // Open base image in new document await pea.openFromURL('https://example.com/background.jpg', false); // Add logo as overlay layer await pea.openFromURL('https://example.com/overlay.png', true); // Position the overlay await pea.runScript( "\n var layer = app.activeDocument.activeLayer;\n layer.translate(100, 100);\n " ); console.log("Composite created successfully"); } catch (error) { console.error("Failed to create composite:", error); } } ``` -------------------------------- ### Export Image from Photopea Source: https://context7.com/yikuansun/photopeaapi/llms.txt Exports the active document from Photopea into a blob format, supporting PNG and JPG. The resulting blob can be used to create download links or display the image directly in an `` element. This is essential for saving or displaying edited images. The function takes the desired format ('png' or 'jpg') as an argument. ```javascript // Export as PNG and create download link try { const blob = await pea.exportImage("png"); const url = URL.createObjectURL(blob); const downloadLink = document.createElement('a'); downloadLink.href = url; downloadLink.download = 'edited-image.png'; downloadLink.textContent = 'Download PNG'; document.body.appendChild(downloadLink); console.log("Export successful, size:", blob.size, "bytes"); } catch (error) { console.error("Export failed:", error); } // Export as JPG and display in img element try { const blob = await pea.exportImage("jpg"); const url = URL.createObjectURL(blob); const img = document.createElement('img'); img.src = url; img.style.maxWidth = '100%'; document.body.appendChild(img); console.log("Image displayed successfully"); } catch (error) { console.error("Failed to display image:", error); } // Complete workflow: open, edit, and export async function processImage(imageUrl) { try { const pea = await Photopea.createEmbed(container); // Open image await pea.openFromURL(imageUrl, false); // Apply brightness adjustment await pea.runScript( "\n var idBrgh = stringIDToTypeID(\"brightnessEvent\");\n var desc = new ActionDescriptor();\n desc.putInteger(stringIDToTypeID(\"brightness\"), 20);\n executeAction(idBrgh, desc, DialogModes.NO);\n " ); // Export result const blob = await pea.exportImage("png"); const url = URL.createObjectURL(blob); return url; } catch (error) { console.error("Image processing failed:", error); return null; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.