Skip to content

Instantly share code, notes, and snippets.

@yikuansun
Last active February 21, 2024 13:46
Show Gist options
  • Save yikuansun/c0f1a602b4e9d4e344a41c4f49ded3bf to your computer and use it in GitHub Desktop.
Save yikuansun/c0f1a602b4e9d4e344a41c4f49ded3bf to your computer and use it in GitHub Desktop.
Useful algorithms for Photopea plugin development
// uses Photopea.js
var addImageAndWait = async function(contentWindow, imgURI) {
return new Promise(async function(resolve) {
var layerCountOld = "done";
while (layerCountOld == "done") layerCountOld = (await Photopea.runScript(contentWindow, `app.echoToOE(app.activeDocument.layers.length)`))[0];
var layerCountNew = layerCountOld;
await Photopea.runScript(contentWindow, `app.open("${imgURI}", null, true);`);
var layerCheckInterval = async function () {
layerCountNew = (await Photopea.runScript(contentWindow, `app.echoToOE(app.activeDocument.layers.length)`))[0];
if (layerCountNew == layerCountOld + 1) {
resolve();
return;
}
else setTimeout(layerCheckInterval, 50);
};
layerCheckInterval();
});
};
// uses Photopea.js
var getDocumentAsImage = async function(contentWindow) {
// returns Image object containing image data from Photopea document
return new Promise(async function(resolve) {
Photopea.runScript(contentWindow, "app.activeDocument.saveToOE('png')").then(function(data) {
var buffer = data[0];
var fR = new FileReader();
fR.addEventListener("load", function(e) {
let img = new Image();
img.src = e.target.result;
resolve(img);
});
fR.readAsDataURL(new Blob([buffer], { type: "image/png" }));
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment