Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Image export: resolution, format and JPG quality settings

Bitticd0ea8e3ff23
diff --git a/src-tauri/src/commands/artifacts.rs b/src-tauri/src/commands/artifacts.rs
index 4785748..d4fa821 100644
--- a/src-tauri/src/commands/artifacts.rs
+++ b/src-tauri/src/commands/artifacts.rs
@@ -223,14 +223,38 @@ pub(crate) fn write_generated_image_frame(
})
}
+/// How the Export tab asks for the image: its file format, its pixel size
+/// (the generated size when absent) and, for JPEG, the quality 1–100.
+#[derive(Debug, Clone, Copy, Default, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct ImageExportOptions {
+ pub format: Option<ImageExportFormat>,
+ pub width: Option<u32>,
+ pub height: Option<u32>,
+ pub quality: Option<u8>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub(crate) enum ImageExportFormat {
+ Jpg,
+ Png,
+}
+
+/// The quality generated JPEGs are written at: exporting at this or above,
+/// unresized, cannot gain anything over the file itself, so it is copied.
+const GENERATED_JPEG_QUALITY: u8 = 95;
+
#[tauri::command]
pub(crate) async fn export_generated_image(
app: AppHandle,
folder_path: String,
relative_path: String,
+ options: Option<ImageExportOptions>,
) -> Result<bool, String> {
tauri::async_runtime::spawn_blocking(move || {
use tauri_plugin_dialog::DialogExt;
+ let options = options.unwrap_or_default();
let root = ProjectRoot::open(&folder_path)?;
let source = root.existing(&relative_path)?;
if !relative_path.starts_with("media/generated/")
@@ -238,32 +262,55 @@ pub(crate) async fn export_generated_image(
{
return Err("Choose a generated JPEG or PNG image to export.".into());
}
- let Some(destination) = app
- .dialog()
- .file()
- .set_title("Export image")
- .add_filter("JPEG image", &["jpg", "jpeg"])
- .add_filter("PNG image", &["png"])
- .set_file_name("image")
- .blocking_save_file()
- else {
+ let dialog = app.dialog().file().set_title("Export image");
+ let dialog = match options.format {
+ Some(ImageExportFormat::Jpg) => dialog.add_filter("JPEG image", &["jpg", "jpeg"]).set_file_name("image.jpg"),
+ Some(ImageExportFormat::Png) => dialog.add_filter("PNG image", &["png"]).set_file_name("image.png"),
+ None => dialog
+ .add_filter("JPEG image", &["jpg", "jpeg"])
+ .add_filter("PNG image", &["png"])
+ .set_file_name("image"),
+ };
+ let Some(destination) = dialog.blocking_save_file() else {
return Ok(false);
};
let destination = destination
.into_path()
.map_err(|_| "Choose a local image destination.")?;
- export_image_file(&source, &destination)?;
+ // The chosen format wins over a mistyped or missing extension.
+ let destination = match options.format {
+ Some(ImageExportFormat::Png) if !has_extension(&destination, &["png"]) => destination.with_extension("png"),
+ Some(ImageExportFormat::Jpg) if !has_extension(&destination, &["jpg", "jpeg"]) => destination.with_extension("jpg"),
+ _ => destination,
+ };
+ export_image_file_with(&source, &destination, options)?;
Ok(true)
})
.await
.map_err(|error| error.to_string())?
}
-/// Copy JPEGs without another lossy encode; PNG exports retain the decoded
-/// source pixels and full resolution. File extensions always match the bytes.
+fn has_extension(path: &std::path::Path, extensions: &[&str]) -> bool {
+ path.extension()
+ .and_then(|value| value.to_str())
+ .is_some_and(|value| extensions.iter().any(|candidate| value.eq_ignore_ascii_case(candidate)))
+}
+
+/// Export at the generated size and default quality; see export_image_file_with.
pub(crate) fn export_image_file(
source: &std::path::Path,
destination: &std::path::Path,
+) -> Result<(), String> {
+ export_image_file_with(source, destination, ImageExportOptions::default())
+}
+
+/// Copy the file untouched when nothing would change (same format, same size,
+/// and for JPEG no quality below the one it was written at); otherwise decode,
+/// resize with Lanczos3 and encode. File extensions always match the bytes.
+pub(crate) fn export_image_file_with(
+ source: &std::path::Path,
+ destination: &std::path::Path,
+ options: ImageExportOptions,
) -> Result<(), String> {
let destination = if destination.extension().is_none() {
destination.with_extension("jpg")
@@ -278,21 +325,37 @@ pub(crate) fn export_image_file(
if !matches!(extension.as_str(), "jpg" | "jpeg" | "png") {
return Err("Choose a .jpg, .jpeg or .png filename for the exported image.".into());
}
+ let quality = options.quality.unwrap_or(GENERATED_JPEG_QUALITY).clamp(1, 100);
let bytes = fs::read(source).map_err(|error| format!("Could not read image: {error}"))?;
let source_format = image::guess_format(&bytes).map_err(|error| format!("Could not read image format: {error}"))?;
let target_format = if extension == "png" { image::ImageFormat::Png } else { image::ImageFormat::Jpeg };
- let bytes = if source_format != target_format {
- let image = image::load_from_memory_with_format(&bytes, source_format)
+ let (source_width, source_height) = image::ImageReader::with_format(std::io::Cursor::new(&bytes), source_format)
+ .into_dimensions()
+ .map_err(|error| format!("Could not read image size: {error}"))?;
+ let width = options.width.unwrap_or(source_width);
+ let height = options.height.unwrap_or(source_height);
+ if width == 0 || height == 0 || width > 16_384 || height > 16_384 {
+ return Err("Choose an export size between 1 and 16384 pixels.".into());
+ }
+ let resized = (width, height) != (source_width, source_height);
+ let unchanged = source_format == target_format
+ && !resized
+ && (target_format == image::ImageFormat::Png || quality >= GENERATED_JPEG_QUALITY);
+ let bytes = if unchanged {
+ bytes
+ } else {
+ let mut image = image::load_from_memory_with_format(&bytes, source_format)
.map_err(|error| format!("Could not decode image: {error}"))?;
+ if resized {
+ image = image.resize_exact(width, height, image::imageops::FilterType::Lanczos3);
+ }
let mut encoded = std::io::Cursor::new(Vec::new());
if target_format == image::ImageFormat::Jpeg {
- image::codecs::jpeg::JpegEncoder::new_with_quality(&mut encoded, 95).encode_image(&image.to_rgb8()).map_err(|error| error.to_string())?;
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut encoded, quality).encode_image(&image.to_rgb8()).map_err(|error| error.to_string())?;
} else {
image.write_to(&mut encoded, target_format).map_err(|error| format!("Could not encode PNG: {error}"))?;
}
encoded.into_inner()
- } else {
- bytes
};
crate::storage::atomic::write_atomically(&destination, &bytes)
}
diff --git a/src-tauri/src/tests/images.rs b/src-tauri/src/tests/images.rs
index 4f65d80..ba86998 100644
--- a/src-tauri/src/tests/images.rs
+++ b/src-tauri/src/tests/images.rs
@@ -115,6 +115,30 @@ fn image_export_writes_real_png_or_copies_jpeg_without_changing_pixels_or_resolu
assert_eq!(fs::read(source).unwrap(), jpeg);
}
+#[test]
+fn image_export_resizes_and_reencodes_at_the_chosen_quality() {
+ use crate::commands::artifacts::{export_image_file_with, ImageExportFormat, ImageExportOptions};
+ let folder = project_folder();
+ let root = folder.path().to_string_lossy();
+ let rgba: Vec<u8> = (0..128 * 80).flat_map(|index| [(index % 256) as u8, (index / 7 % 256) as u8, 160, 255]).collect();
+ let saved = write_generated_image_frame(&root, "resize-test", 128, 80, &rgba).unwrap();
+ let source = folder.path().join(saved.relative_path);
+ let original = fs::read(&source).unwrap();
+ let half = folder.path().join("half.png");
+ export_image_file_with(&source, &half, ImageExportOptions { format: Some(ImageExportFormat::Png), width: Some(64), height: Some(40), quality: None }).unwrap();
+ assert_eq!(::image::image_dimensions(&half).unwrap(), (64, 40));
+ let low = folder.path().join("low.jpg");
+ export_image_file_with(&source, &low, ImageExportOptions { format: Some(ImageExportFormat::Jpg), width: None, height: None, quality: Some(20) }).unwrap();
+ let low = fs::read(low).unwrap();
+ assert_ne!(low, original);
+ assert!(low.len() < original.len());
+ let best = folder.path().join("best.jpg");
+ export_image_file_with(&source, &best, ImageExportOptions { format: Some(ImageExportFormat::Jpg), width: None, height: None, quality: Some(100) }).unwrap();
+ assert_eq!(fs::read(best).unwrap(), original);
+ let zero = folder.path().join("zero.jpg");
+ assert!(export_image_file_with(&source, &zero, ImageExportOptions { format: None, width: Some(0), height: Some(40), quality: None }).is_err());
+}
+
#[test]
fn image_tree_survives_folder_creation_save_and_reopen() {
let root = tempfile::tempdir().unwrap();
diff --git a/src/components/ImageProject.integration.test.tsx b/src/components/ImageProject.integration.test.tsx
index 8e58e14..393206b 100644
--- a/src/components/ImageProject.integration.test.tsx
+++ b/src/components/ImageProject.integration.test.tsx
@@ -35,12 +35,14 @@ it("exports the selected image from the Export tab and handles cancellation and
fireEvent.click(screen.getByRole("button", { name: "View Second" }));
fireEvent.click(within(screen.getByRole("tablist", { name: "Project views" })).getByRole("tab", { name: /Export/ }));
const settings = screen.getByRole("region", { name: "Export settings" });
- expect(within(settings).getByText("JPG or PNG, chosen when saving")).toBeInTheDocument();
- expect(within(settings).getByText("1024 × 768 px")).toBeInTheDocument();
+ expect(within(settings).getByRole("combobox", { name: "Format" })).toHaveTextContent("JPG");
+ expect(within(settings).getByRole("combobox", { name: "Resolution" })).toHaveTextContent("1024 × 768 (original)");
expect(screen.getByRole("region", { name: "Image preview" })).toContainElement(screen.getByRole("img", { name: /Second/ }));
const button = within(settings).getByRole("button", { name: "Export…" });
fireEvent.click(button);
- await waitFor(() => expect(invoke).toHaveBeenCalledWith("export_generated_image", { folderPath: "D:/Images", relativePath: "media/generated/Second.jpg" }));
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith("export_generated_image", {
+ folderPath: "D:/Images", relativePath: "media/generated/Second.jpg", options: { format: "jpg", width: 1024, height: 768, quality: 90 },
+ }));
expect(within(settings).getByRole("button", { name: "Exporting…" })).toBeDisabled();
await act(async () => complete(false));
expect(button).toBeEnabled();
diff --git a/src/components/workspace/ImageExportView.test.tsx b/src/components/workspace/ImageExportView.test.tsx
index 311d9ae..4017b12 100644
--- a/src/components/workspace/ImageExportView.test.tsx
+++ b/src/components/workspace/ImageExportView.test.tsx
@@ -1,10 +1,11 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
-import { cleanup, render, screen, within } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import fixture from "../../../fixtures/project-v1-image.json";
import { parseProjectConfig, type ProjectConfig } from "../../lib/project";
import * as persistence from "../../lib/persistence";
+import { invoke } from "@tauri-apps/api/core";
import { ImageExportView } from "./ImageExportView";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
@@ -26,7 +27,7 @@ it("lays the page out like the video export: stage, splitter, settings pane with
expect(screen.getByRole("separator", { name: "Resize export settings" })).toBeInTheDocument();
const settings = screen.getByRole("region", { name: "Export settings" });
expect(settings.querySelector(".export-settings__scroll")?.firstElementChild).toHaveClass("ui-prop-section");
- expect(within(settings).getByText("2048 × 1152 px")).toBeInTheDocument();
+ expect(within(settings).getByRole("combobox", { name: "Resolution" })).toHaveTextContent("2048 × 1152 (original)");
const foot = settings.querySelector(".export-settings__foot")!;
expect(within(foot as HTMLElement).getByRole("button", { name: "Export…" })).toBeEnabled();
expect(screen.queryByText("Nothing to export yet")).not.toBeInTheDocument();
@@ -40,3 +41,20 @@ it("refuses to export a draft and says why", () => {
expect(button).toHaveAttribute("data-tooltip", "This image is still a draft. Generate it before exporting.");
expect(screen.getByText("The image is a draft")).toBeInTheDocument();
});
+
+it("sends the chosen size, format and JPG quality, and hides quality for PNG", async () => {
+ vi.spyOn(persistence, "isTauri").mockReturnValue(true);
+ vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);
+ vi.mocked(invoke).mockResolvedValue(true);
+ render(<ImageExportView config={withOutput({ width: 2048, height: 1152 })} folderPath="D:/Images" />);
+ fireEvent.change(screen.getByRole("slider", { name: "JPG quality" }), { target: { value: "60" } });
+ fireEvent.click(screen.getByRole("button", { name: "Export…" }));
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith("export_generated_image", {
+ folderPath: "D:/Images", relativePath: "media/generated/out.png",
+ options: { format: "jpg", width: 2048, height: 1152, quality: 60 },
+ }));
+ expect(JSON.parse(localStorage.getItem("slopus.image-export.v1")!)).toEqual({ format: "jpg", quality: 60 });
+ fireEvent.click(screen.getByRole("combobox", { name: "Format" }));
+ fireEvent.click(screen.getByRole("option", { name: /PNG/ }));
+ expect(screen.queryByRole("slider", { name: "JPG quality" })).toBeNull();
+});
diff --git a/src/components/workspace/ImageExportView.tsx b/src/components/workspace/ImageExportView.tsx
index 469fd40..065afcc 100644
--- a/src/components/workspace/ImageExportView.tsx
+++ b/src/components/workspace/ImageExportView.tsx
@@ -1,16 +1,32 @@
import { invoke } from "@tauri-apps/api/core";
import { useState } from "react";
-import type { ProjectConfig } from "../../lib/project";
+import { outputDimensions } from "../../lib/export";
+import { PROJECT_RESOLUTIONS, type ProjectConfig } from "../../lib/project";
import { isTauri } from "../../lib/persistence";
-import { EmptyState, InfoBar, PropSection, Splitter, tooltipProps, usePaneSize } from "../ui";
+import { ComboBox, EmptyState, InfoBar, PropRow, PropSection, Slider, Splitter, tooltipProps, usePaneSize } from "../ui";
import { Image32 } from "../ui/icons";
import { ReferenceImage } from "./ReferenceImage";
/* The image project's Export tab: the same page as the video export (see
export.css) — the image on the stage, filling it, and the resizable settings
pane on the right opening straight on its first section, with Export… pinned
- at its foot. For now Export… only opens the Save dialog (JPG or PNG is picked
- there); the pane is where output settings will grow. */
+ at its foot. Output sets the size (the image's own, or a rung of the project
+ ladder at its aspect), the format and, for JPG, the quality; Export… then
+ asks where to save. Format and quality are remembered across projects. */
+
+type ImageFormat = "jpg" | "png";
+const STORAGE_KEY = "slopus.image-export.v1";
+const DEFAULT_QUALITY = 90;
+
+function loadPreferences(): { format: ImageFormat; quality: number } {
+ try {
+ const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "{}") as { format?: unknown; quality?: unknown };
+ const quality = typeof saved.quality === "number" && saved.quality >= 1 && saved.quality <= 100 ? Math.round(saved.quality) : DEFAULT_QUALITY;
+ return { format: saved.format === "png" ? "png" : "jpg", quality };
+ } catch { return { format: "jpg", quality: DEFAULT_QUALITY }; }
+}
+
+const sizeKey = (width: number, height: number) => `${width}x${height}`;
export function ImageExportView({ config, folderPath }: { config: ProjectConfig; folderPath: string }) {
const settingsPane = usePaneSize("export.settings", 340, { min: 280, max: 560 });
const [exporting, setExporting] = useState(false);
@@ -25,18 +41,39 @@ export function ImageExportView({ config, folderPath }: { config: ProjectConfig;
: !desktop ? "Exporting is available in the Slopus desktop app."
: null;
const disabled = blocker !== null || exporting;
- const size = output?.width && output?.height ? `${output.width} × ${output.height}` : null;
+ const [preferences, setPreferences] = useState(loadPreferences);
+ const choose = (patch: Partial<typeof preferences>) => {
+ const next = { ...preferences, ...patch };
+ setPreferences(next);
+ try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch { /* remembered for this session only */ }
+ };
+
+ /* The image's own size first, then the ladder at the project's aspect —
+ the same sizes the video export offers — skipping a rung that is it. */
+ const original = output?.width && output?.height ? { width: output.width, height: output.height } : null;
+ const sizes = [
+ ...(original ? [{ ...original, label: `${original.width} × ${original.height} (original)` }] : []),
+ ...PROJECT_RESOLUTIONS.map((resolution) => outputDimensions(resolution, config.settings.aspectRatio))
+ .filter((size) => !original || sizeKey(size.width, size.height) !== sizeKey(original.width, original.height))
+ .map((size) => ({ ...size, label: `${size.width} × ${size.height}` })),
+ ];
+ const [chosenSize, setChosenSize] = useState<string | null>(null);
+ const size = sizes.find((candidate) => sizeKey(candidate.width, candidate.height) === chosenSize) ?? sizes[0];
const exportImage = async () => {
if (!output?.relativePath || disabled) return;
setExporting(true); setError(null);
- try { await invoke("export_generated_image", { folderPath, relativePath: output.relativePath }); }
+ try {
+ await invoke("export_generated_image", {
+ folderPath,
+ relativePath: output.relativePath,
+ options: { format: preferences.format, width: size?.width, height: size?.height, quality: preferences.format === "jpg" ? preferences.quality : undefined },
+ });
+ }
catch (reason) { setError(String(reason)); }
finally { setExporting(false); }
};
- const facts: [string, string][] = [["Format", "JPG or PNG, chosen when saving"]];
- if (size) facts.push(["Size", `${size} px`]);
return <div className="export-view" style={settingsPane.style}>
<h1 className="sr-only">Export</h1>
@@ -57,12 +94,29 @@ export function ImageExportView({ config, folderPath }: { config: ProjectConfig;
<section id="image-export-settings" className="export-settings" aria-label="Export settings">
<div className="export-settings__scroll">
<PropSection title="Output" persistKey="export.image.output">
- <dl className="export-summary">
- {facts.map(([term, value]) => <div key={term}>
- <dt>{term}</dt>
- <dd>{value}</dd>
- </div>)}
- </dl>
+ <PropRow label="Resolution" htmlFor="image-export-resolution">
+ <ComboBox
+ id="image-export-resolution"
+ value={size ? sizeKey(size.width, size.height) : ""}
+ disabled={exporting || sizes.length === 0}
+ placeholder="Generate an image first"
+ onChange={setChosenSize}
+ options={sizes.map((candidate) => ({ value: sizeKey(candidate.width, candidate.height), label: candidate.label }))}
+ />
+ </PropRow>
+ <PropRow label="Format" htmlFor="image-export-format">
+ <ComboBox
+ id="image-export-format"
+ value={preferences.format}
+ disabled={exporting}
+ onChange={(value) => choose({ format: value as ImageFormat })}
+ options={[{ value: "jpg", label: "JPG" }, { value: "png", label: "PNG · lossless" }]}
+ />
+ </PropRow>
+ {preferences.format === "jpg" && <PropRow label="Quality" value={preferences.quality} defaultValue={DEFAULT_QUALITY} onReset={exporting ? undefined : () => choose({ quality: DEFAULT_QUALITY })} resetLabel="Reset quality">
+ <Slider aria-label="JPG quality" min={1} max={100} step={1} value={preferences.quality} disabled={exporting} onChange={(quality) => choose({ quality })} />
+ <span className="export-quality__value">{preferences.quality}</span>
+ </PropRow>}
</PropSection>
<div className="export-messages">
{blocker && <InfoBar severity="informational" title="Nothing to export yet" message={blocker} />}
@@ -76,7 +130,7 @@ export function ImageExportView({ config, folderPath }: { config: ProjectConfig;
className="primary-button"
disabled={disabled}
onClick={() => void exportImage()}
- {...tooltipProps(exporting ? "Export is running" : blocker ?? "Save the image as JPG or PNG")}
+ {...tooltipProps(exporting ? "Export is running" : blocker ?? `Save the image as ${preferences.format.toUpperCase()}`)}
>{exporting ? "Exporting…" : "Export…"}</button>
</div>
</div>
diff --git a/src/styles/export.css b/src/styles/export.css
index cea5db5..f7b3fbf 100644
--- a/src/styles/export.css
+++ b/src/styles/export.css
@@ -295,6 +295,16 @@ img.export-image {
/* The summary as a label/value list, one line per fact, on the PropRow grid:
the --prop-label column, the value, and the empty reset column. */
+/* The image export's JPG quality, read out beside its slider. */
+.export-quality__value {
+ min-width: 32px;
+ flex: none;
+ color: var(--text-primary);
+ font-size: var(--text-xs);
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+}
+
.export-summary {
margin: 0;
display: grid;