Skip to content

Free open-source image editor for the browser

Add image export

Rodrigo63e4328fc7cb
diff --git a/src/app/editor/renderer/renderer.ts b/src/app/editor/renderer/renderer.ts
index f236aec..2427583 100644
--- a/src/app/editor/renderer/renderer.ts
+++ b/src/app/editor/renderer/renderer.ts
@@ -38,7 +38,7 @@ export function createRenderer(gpu: Gpu, source: Target) {
const applyCurve = effect(gpu, curvesShader, {
set: { source: adjusted.color, curve },
});
- const bins = histogram(gpu);
+ let bins: ReturnType<typeof histogram> | undefined;
const display = effect(gpu, shader, {
set: {
sourceSampler: sampler(gpu, { magFilter: "linear", minFilter: "linear" }),
@@ -60,6 +60,7 @@ export function createRenderer(gpu: Gpu, source: Target) {
if (disposed || outputs.size === 0) {
return;
}
+ bins ??= histogram(gpu);
const counts = await bins.read(image, space);
if (!disposed) {
for (const draw of outputs) {
diff --git a/src/app/editor/sidebar/export-button.tsx b/src/app/editor/sidebar/export-button.tsx
new file mode 100644
index 0000000..1dde7c0
--- /dev/null
+++ b/src/app/editor/sidebar/export-button.tsx
@@ -0,0 +1,21 @@
+import { useRef } from "react";
+import Button from "@/components/ui/button";
+import ExportSettings from "./export-settings";
+
+export default function ExportButton() {
+ const dialog = useRef<HTMLDialogElement>(null);
+ return (
+ <section className="shrink-0 p-4">
+ <Button className="w-full" onClick={() => dialog.current?.showModal()}>
+ Export
+ </Button>
+ <dialog
+ ref={dialog}
+ aria-label="Export image"
+ className="m-auto w-[360px] max-w-[calc(100%-2rem)] overflow-hidden rounded-xl border border-black bg-neutral-800 p-0 text-neutral-100 shadow-2xl backdrop:bg-black/50 backdrop:backdrop-blur-sm"
+ >
+ <ExportSettings onClose={() => dialog.current?.close()} />
+ </dialog>
+ </section>
+ );
+}
diff --git a/src/app/editor/sidebar/export-settings.tsx b/src/app/editor/sidebar/export-settings.tsx
new file mode 100644
index 0000000..368d013
--- /dev/null
+++ b/src/app/editor/sidebar/export-settings.tsx
@@ -0,0 +1,110 @@
+import { useRef, useState } from "react";
+import { useGpu } from "vgpu-react";
+import { exportImage } from "@/app/export-image";
+import Button from "@/components/ui/button";
+import { Slider } from "@/components/ui/slider";
+
+const formats = [
+ { value: "png", description: "Lossless detail" },
+ { value: "jpeg", description: "Smaller files" },
+] as const;
+
+export default function ExportSettings({ onClose }: { onClose: () => void }) {
+ const gpu = useGpu();
+ const [format, setFormat] = useState<"png" | "jpeg">("png");
+ const [quality, setQuality] = useState(90);
+ const [error, setError] = useState("");
+ const exporting = useRef(false);
+ const save = async () => {
+ if (exporting.current) {
+ return;
+ }
+ exporting.current = true;
+ setError("");
+ try {
+ const options = format === "png" ? { format } : { format, quality };
+ const file = await exportImage(gpu, options);
+ const url = URL.createObjectURL(file);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = file.name;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ onClose();
+ } catch (error) {
+ setError(
+ error instanceof Error ? error.message : "Couldn't export image.",
+ );
+ } finally {
+ exporting.current = false;
+ }
+ };
+ return (
+ <div className="divide-y divide-black shadow-ridge">
+ <header className="px-4 py-3">
+ <h2 className="font-medium">Export image</h2>
+ <p className="mt-1 text-xs text-neutral-400">
+ Full resolution. All your edits included.
+ </p>
+ </header>
+ <div className="space-y-4 p-4">
+ <fieldset>
+ <legend className="mb-2 text-xs text-neutral-400">Format</legend>
+ <div className="grid grid-cols-2 gap-2">
+ {formats.map(({ value, description }) => (
+ <label key={value} className="cursor-pointer">
+ <input
+ className="peer sr-only"
+ type="radio"
+ name="export-format"
+ value={value}
+ checked={format === value}
+ onChange={() => setFormat(value)}
+ />
+ <span className="flex flex-col gap-1 rounded-lg border border-transparent px-3 py-2 text-neutral-400 hover:bg-neutral-700/30 peer-checked:border-neutral-500 peer-checked:bg-neutral-700 peer-checked:text-neutral-100 peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-neutral-400">
+ <span className="text-sm font-medium uppercase">{value}</span>
+ <span className="text-xs text-neutral-400">
+ {description}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ <div className="min-h-16">
+ {format === "jpeg" && (
+ <>
+ <Slider
+ label="Quality"
+ value={quality}
+ onChange={setQuality}
+ min={1}
+ max={100}
+ />
+ <p className="mt-2 text-xs text-neutral-500">
+ Lower quality makes a smaller file.
+ </p>
+ </>
+ )}
+ {format === "png" && (
+ <p className="text-xs leading-relaxed text-neutral-400">
+ Preserves every detail without compression loss. Best for keeping
+ a finished edit.
+ </p>
+ )}
+ </div>
+ {error && (
+ <p className="text-sm text-red-400" role="alert">
+ {error}
+ </p>
+ )}
+ </div>
+ <footer className="flex justify-end gap-2 bg-neutral-900/40 px-4 py-3">
+ <Button variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button onClick={save}>Save image</Button>
+ </footer>
+ </div>
+ );
+}
diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/sidebar/index.tsx
index 05ed9dd..17c9269 100644
--- a/src/app/editor/sidebar/index.tsx
+++ b/src/app/editor/sidebar/index.tsx
@@ -1,17 +1,21 @@
import ResizablePanel from "@/components/ui/resizable-panel";
import AdjustmentControls from "./adjustment-controls";
import Curves from "./curves";
+import ExportButton from "./export-button";
import Histogram from "./histogram";
export default function Sidebar() {
return (
<ResizablePanel>
- <div className="flex h-full flex-col divide-y divide-black overflow-y-auto">
- <section className="bg-neutral-900 p-0.5 pb-0">
- <Histogram />
- </section>
- <AdjustmentControls />
- <Curves />
+ <div className="flex h-full flex-col divide-y divide-black">
+ <div className="min-h-0 flex-1 divide-y divide-black overflow-y-auto">
+ <section className="bg-neutral-900 p-0.5 pb-0">
+ <Histogram />
+ </section>
+ <AdjustmentControls />
+ <Curves />
+ </div>
+ <ExportButton />
</div>
</ResizablePanel>
);
diff --git a/src/app/export-image.ts b/src/app/export-image.ts
new file mode 100644
index 0000000..d0e5bef
--- /dev/null
+++ b/src/app/export-image.ts
@@ -0,0 +1,47 @@
+import { frame, type Gpu, surface } from "vgpu";
+import { createRenderer } from "@/app/editor/renderer/renderer";
+import { useScene } from "@/app/scene";
+
+export type ExportOptions =
+ | { format: "png" }
+ | { format: "jpeg"; quality: number };
+
+/** Renders a snapshot of the current edits at the original image dimensions. */
+export async function exportImage(
+ gpu: Gpu,
+ options: ExportOptions = { format: "png" },
+) {
+ if (options.format !== "png" && options.format !== "jpeg") {
+ throw new Error("Choose PNG or JPEG.");
+ }
+ if (
+ options.format === "jpeg" &&
+ (!Number.isFinite(options.quality) ||
+ options.quality < 1 ||
+ options.quality > 100)
+ ) {
+ throw new Error("JPEG quality must be between 1 and 100.");
+ }
+ const scene = useScene.getState();
+ const source = scene.source;
+ if (!source?.image) {
+ throw new Error("Load an image before exporting.");
+ }
+ const [width, height] = source.image.size;
+ const canvas = new OffscreenCanvas(width, height);
+ const output = surface(gpu, canvas, { size: [width, height], dpr: 1 });
+ const renderer = createRenderer(gpu, source.image);
+ try {
+ renderer.attachCanvas(output, { zoom: 1, pan: [0, 0], percent: 100 });
+ frame(gpu, (frame) => renderer.render(frame, scene));
+ const blob = await canvas.convertToBlob({
+ type: `image/${options.format}`,
+ quality: options.format === "jpeg" ? options.quality / 100 : undefined,
+ });
+ const extension = options.format === "jpeg" ? "jpg" : "png";
+ return new File([blob], `export.${extension}`, { type: blob.type });
+ } finally {
+ renderer.dispose();
+ output.dispose();
+ }
+}
diff --git a/src/app/scene/controls.ts b/src/app/scene/controls.ts
index 59c0f57..764e53a 100644
--- a/src/app/scene/controls.ts
+++ b/src/app/scene/controls.ts
@@ -1,5 +1,6 @@
import { useEffect, useMemo } from "react";
import { useGpu } from "vgpu-react";
+import { type ExportOptions, exportImage } from "@/app/export-image";
import { useScene } from ".";
function getState() {
@@ -24,6 +25,7 @@ export function useControls() {
loadImage: (file: File) => useScene.getState().loadImage(gpu, file),
setAdjustments: useScene.getState().setAdjustments,
setCurve: useScene.getState().setCurve,
+ exportImage: (options?: ExportOptions) => exportImage(gpu, options),
getState,
}),
[gpu],
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 4db4317..16cd452 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -1,16 +1,30 @@
+import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
import type { ComponentProps } from "react";
+const button = cva(
+ "cursor-pointer rounded-lg border px-3 py-2 transition-colors focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-neutral-400",
+ {
+ variants: {
+ variant: {
+ default:
+ "border-black bg-neutral-700 text-neutral-100 shadow-ridge hover:bg-neutral-600 active:bg-neutral-700 active:shadow-groove",
+ ghost:
+ "border-transparent text-neutral-400 hover:bg-neutral-700/50 hover:text-neutral-100 active:bg-neutral-700",
+ },
+ },
+ defaultVariants: { variant: "default" },
+ },
+);
+
export default function Button({
className,
+ variant,
...props
-}: ComponentProps<"button">) {
+}: ComponentProps<"button"> & VariantProps<typeof button>) {
return (
<button
- className={cn(
- "cursor-pointer rounded-lg border border-black bg-neutral-700 px-3 py-2 text-neutral-100 shadow-ridge hover:bg-neutral-600 active:bg-neutral-700 active:shadow-groove focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-neutral-400 transition-colors",
- className,
- )}
+ className={cn(button({ variant }), className)}
type="button"
{...props}
/>
diff --git a/tests/export.e2e.ts b/tests/export.e2e.ts
new file mode 100644
index 0000000..3b72625
--- /dev/null
+++ b/tests/export.e2e.ts
@@ -0,0 +1,157 @@
+import { readFile } from "node:fs/promises";
+import { expect, test } from "@playwright/test";
+
+test("exports full-resolution PNGs with current edits through the API and button", async ({
+ page,
+}) => {
+ const errors: string[] = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ page.on("console", (message) => {
+ if (message.type() === "error") errors.push(message.text());
+ });
+ await page.goto("/");
+ await page.waitForFunction(() => window.openlight);
+ await page.evaluate(async () => {
+ await window.openlight.loadImage(
+ new File(
+ [
+ '<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800"><rect width="1200" height="800" fill="#808080"/><rect width="100" height="100" fill="black"/></svg>',
+ ],
+ "photo.original.svg",
+ { type: "image/svg+xml" },
+ ),
+ );
+ });
+ const button = page.getByRole("button", { name: "Export", exact: true });
+ await expect(button).toBeVisible();
+ const original = await page.evaluate(async () => {
+ const file = await window.openlight.exportImage();
+ const image = await createImageBitmap(file);
+ const canvas = new OffscreenCanvas(image.width, image.height);
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Cannot read exported image.");
+ context.drawImage(image, 0, 0);
+ image.close();
+ return [...context.getImageData(600, 400, 1, 1).data];
+ });
+ expect(original).toEqual([128, 128, 128, 255]);
+ await page.evaluate(() => {
+ window.openlight.setAdjustments({ exposure: 1 });
+ window.openlight.setCurve([
+ { x: 0, y: 0 },
+ { x: 0.5, y: 0.75 },
+ { x: 1, y: 1 },
+ ]);
+ });
+ // The viewport may be zoomed; exporting still includes the original image edges.
+ await page.locator("canvas").hover();
+ await page.keyboard.down("Control");
+ await page.mouse.wheel(0, -100);
+ await page.keyboard.up("Control");
+ const pending = page.waitForEvent("download");
+ await button.click();
+ await page.getByRole("button", { name: "Save image" }).click();
+ const download = await pending;
+ expect(download.suggestedFilename()).toBe("export.png");
+ const path = await download.path();
+ if (!path) throw new Error("Missing downloaded PNG.");
+ const pixels = await page.evaluate(
+ async (bytes) => {
+ const image = await createImageBitmap(
+ new Blob([new Uint8Array(bytes)], { type: "image/png" }),
+ );
+ const canvas = new OffscreenCanvas(image.width, image.height);
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Cannot read exported image.");
+ context.drawImage(image, 0, 0);
+ image.close();
+ return {
+ size: [canvas.width, canvas.height],
+ center: [...context.getImageData(600, 400, 1, 1).data],
+ corner: [...context.getImageData(10, 10, 1, 1).data],
+ };
+ },
+ [...(await readFile(path))],
+ );
+ expect(pixels.size).toEqual([1200, 800]);
+ expect(pixels.corner).toEqual([0, 0, 0, 255]);
+ // Exposure alone produces about 175; the lifted curve must also be present.
+ expect(pixels.center[0]).toBeGreaterThan(190);
+ expect(pixels.center[0]).toBeLessThan(255);
+ expect(pixels.center[3]).toBe(255);
+ await expect(button).toBeEnabled();
+ expect(errors).toEqual([]);
+});
+
+test("export dialog selects JPEG quality, preserves settings, and dismisses", async ({
+ page,
+}) => {
+ await page.goto("/");
+ await page.waitForFunction(() => window.openlight);
+ await page.evaluate(async () => {
+ const canvas = new OffscreenCanvas(256, 256);
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Cannot create test image.");
+ const pixels = context.createImageData(256, 256);
+ for (let i = 0; i < pixels.data.length; i += 4) {
+ pixels.data[i] = (i * 31) % 251;
+ pixels.data[i + 1] = (i * 17) % 253;
+ pixels.data[i + 2] = (i * 7) % 255;
+ pixels.data[i + 3] = 255;
+ }
+ context.putImageData(pixels, 0, 0);
+ await window.openlight.loadImage(
+ new File([await canvas.convertToBlob()], "texture.png", {
+ type: "image/png",
+ }),
+ );
+ });
+ const trigger = page.getByRole("button", { name: "Export", exact: true });
+ const dialog = page.getByRole("dialog", { name: "Export image" });
+ await trigger.click();
+ await expect(dialog.getByRole("radio", { name: /png/i })).toBeChecked();
+ await expect(dialog.getByRole("slider", { name: "Quality" })).toBeHidden();
+ await dialog.getByText("Smaller files", { exact: true }).click();
+ const quality = dialog.getByRole("slider", { name: "Quality" });
+ await expect(quality).toHaveValue("90");
+ const sizes: number[] = [];
+ for (const value of [20, 95]) {
+ await dialog.getByRole("textbox", { name: "Quality" }).fill(String(value));
+ await dialog.getByRole("textbox", { name: "Quality" }).press("Enter");
+ const pending = page.waitForEvent("download");
+ await dialog.getByRole("button", { name: "Save image" }).click();
+ const download = await pending;
+ expect(download.suggestedFilename()).toBe("export.jpg");
+ const path = await download.path();
+ if (!path) throw new Error("Missing JPEG download.");
+ const bytes = await readFile(path);
+ expect([...bytes.subarray(0, 3)]).toEqual([255, 216, 255]);
+ sizes.push(bytes.length);
+ await expect(dialog).toBeHidden();
+ await expect(trigger).toBeFocused();
+ await trigger.click();
+ await expect(quality).toHaveValue(String(value));
+ }
+ expect(sizes[1]).toBeGreaterThan(sizes[0]);
+ await page.keyboard.press("Escape");
+ await expect(dialog).toBeHidden();
+ await expect(trigger).toBeFocused();
+ await trigger.click();
+ await dialog.getByRole("button", { name: "Cancel" }).click();
+ await expect(dialog).toBeHidden();
+ const result = await page.evaluate(async () => {
+ const file = await window.openlight.exportImage({
+ format: "jpeg",
+ quality: 80,
+ });
+ const image = await createImageBitmap(file);
+ const size = [image.width, image.height];
+ image.close();
+ return { name: file.name, type: file.type, size };
+ });
+ expect(result).toEqual({
+ name: "export.jpg",
+ type: "image/jpeg",
+ size: [256, 256],
+ });
+});