Ptotopea Image Editor Iframe
A simple svelte component to integrate the photopea image editor in your svelte app
Allows you to select an image, send it to the photopea editor in an iframe and get back the edited image.
<script lang="ts">
let base64Image = $state('');
let uriComponent = $derived(
encodeURIComponent(
JSON.stringify({
files: [base64Image],
environment: {
customIO: { save: 'app.activeDocument.saveToOE("png")' },
menus: [[1, 1, 0, 0, 0, 1, 0], 1, 0, 1]
}
})
)
);
let showResult = $state(false);
async function handleImage(event: Event) {
const input = event.target as HTMLInputElement;
if (!input.files || input.files.length === 0) return;
const file = input.files[0];
base64Image = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(file);
});
showResult = false;
}
function arrayBufferToBase64PNG(buffer: ArrayBuffer) {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return 'data:image/png;base64,' + btoa(binary);
}
function handleMessage(event: MessageEvent) {
if (event.origin !== 'https://www.photopea.com') return;
const eventBuffer = event.data;
if (eventBuffer instanceof ArrayBuffer) {
const base64PNG = arrayBufferToBase64PNG(eventBuffer);
base64Image = base64PNG;
showResult = true;
}
}
</script>
<svelte:window onmessage={handleMessage} />
{#if showResult}
<button
onclick={() => {
base64Image = '';
showResult = false;
}}>Select new image</button
>
<img src={base64Image} alt="" />
{:else if !base64Image}
<input type="file" accept="image/*" onchange={handleImage} />
{:else}
<iframe src="https://www.photopea.com#{uriComponent}" title="Photo editor" frameborder="0"
></iframe>
{/if}
<style>
iframe {
width: 100%;
height: 500px;
}
</style>