Add JPEG XL export with a lossless option

Export now offers JPEG XL (8-bit sRGB) next to JPEG, PNG, WebP and 16-bit
TIFF, encoded on-device by libjxl compiled to WebAssembly so the export stays
offline. The codec loads only when a JXL is chosen, the quality slider applies
to the lossy mode, and a lossless switch disables it. The user guide and
changelog describe the format and its current limits (no ICC or XMP yet).

Also adds SECURITY-AUDIT.md with the dependency scan and the review of the
server's trust boundaries.
This commit is contained in:
2026-12-01 14:43:29 +00:00
parent 8b309d9cad
commit 3759b47bc6
13 changed files with 309 additions and 8 deletions
+11
View File
@@ -3,6 +3,17 @@
Dated release notes, newest first. The same entries are summarised on the product Dated release notes, newest first. The same entries are summarised on the product
page; this file is the complete list. page; this file is the complete list.
## Unreleased
### Added
- **JPEG XL export.** The export dialog offers JPEG XL alongside JPEG, PNG, WebP and
16-bit TIFF, with the quality slider and a lossless switch. Files are 8-bit sRGB,
encoded by libjxl compiled to WebAssembly in the app itself, so the export stays
offline and nothing is uploaded. The codec loads only when a JXL is exported. No
ICC profile or XMP metadata is embedded yet, and 16-bit JXL waits on a float-input
encoder build.
## 0.5.3.1 — 1 December 2026 ## 0.5.3.1 — 1 December 2026
Windows and Linux bundles rebuilt. macOS stays at 0.5.1: the app has to be built on Windows and Linux bundles rebuilt. macOS stays at 0.5.1: the app has to be built on
+1 -1
View File
@@ -143,7 +143,7 @@ with a keyword library and reusable metadata presets. Save the current filters a
order as a smart collection. Virtual copies share the master file but keep independent order as a smart collection. Virtual copies share the master file but keep independent
edits; named snapshots preserve alternative looks. edits; named snapshots preserve alternative looks.
**Export and print.** JPEG, PNG, WebP or uncompressed 16-bit TIFF; quality; resize by **Export and print.** JPEG, PNG, WebP, JPEG XL (8-bit, lossy or lossless) or uncompressed 16-bit TIFF; quality; resize by
long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB, export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB,
Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch
+136
View File
@@ -0,0 +1,136 @@
# Security audit
Date: 1 December 2026 · Version: 0.5.3.1 · Scope: this repository (server, client,
build/release scripts, dependencies). Review was static: dependency scan plus a
targeted read of the server's trust boundaries. No infrastructure, host or
third-party service was tested.
## Summary
No critical or high-severity issue was found in code that ships and runs by
default. The production dependency tree has two `high` advisories that come from
one transitive package (`adm-zip` inside `onnxruntime-node`) and are not
reachable through anything this application does.
Everything else is either a development-only toolchain advisory, a hardening
opportunity, or an operational note.
| Area | Result |
| --- | --- |
| Production dependencies | 0 critical, 0 moderate, 2 high (one transitive package, not reachable) |
| Development dependencies | 2 critical, 3 high, 3 moderate — dev server and test runner only |
| Authentication and sessions | scrypt with per-user salt, random tokens, HttpOnly/SameSite cookies, rate limiting |
| Authorisation | Every `/api/admin/*` route calls `requireAdmin`; gallery routes are token-scoped |
| Injection | No `eval`, no `new Function`, no `innerHTML`/`dangerouslySetInnerHTML`; SQLite access is entirely prepared statements |
| Path traversal | Static and tether paths are resolved and compared against a root; uploads use generated IDs |
| Secret handling | SMTP and bridge credentials AES-256-GCM encrypted at rest; no secrets in the tree |
| Uploads | Global size cap, content-length checked before reading, quota per account |
| Outbound requests | Immich and dashboard URLs are operator-configured, not user-configured |
## Dependency findings
### 1. `adm-zip` — high, transitive (`onnxruntime-node` → `adm-zip`)
Advisories: crafted ZIP triggers a 4 GB allocation; extraction follows
destination symlinks and can overwrite arbitrary files; uncontrolled memory
allocation via a declared size.
Reachability here: `onnxruntime-node` declares `adm-zip` for its own archive
handling. Luminary never extracts a ZIP it did not create: the denoise models are
read from local storage, and the only ZIP code in the app writes archives
(`src/lib/zip.ts`) rather than reading them. No route accepts a ZIP. Impact is
therefore latent rather than exploitable.
Fix: upgrade `onnxruntime-node` 1.23.0 → 1.31.1 (`npm i onnxruntime-node@1.31.1`).
That is the version npm proposes, a non-major bump. Not applied in this pass
because it changes the denoise runtime and needs its own regression run.
### 2. Development toolchain — 2 critical, 3 high, 3 moderate
`vitest`/`tinypool`/`@vitest/mocker` (prototype-pollution gadget to RCE, arbitrary
file read via the Vitest UI server), `vite` (path traversal in optimised-deps
`.map` handling, `launch-editor` NTLM hash disclosure), `esbuild` (dev server
request proxying).
None of these ship: the release bundle is static `dist/` output and the Node
server does not run Vite. They matter only for a machine that runs `npm run dev`
or the Vitest UI while exposed to an untrusted network. Fix by moving to the
current Vite/Vitest majors on a branch, not by a patch bump inside the current
majors.
`npm audit --omit=dev` is the meaningful gate for releases; add it to
`predeploy` if that gate should be enforced.
## Verified controls
- **Password storage**: `scrypt` (`server/auth.mjs`), 32-byte key, per-hash random
salt, compared with `timingSafeEqual`. Non-existent accounts spend the same
scrypt work and return the same message, so the endpoint does not reveal which
addresses are registered.
- **Sessions**: 32-byte random tokens, `HttpOnly`, `SameSite=Lax`, `Secure` when
the request arrived over HTTPS, 30-day lifetime, server-side revocation on logout.
- **Rate limiting**: sign-in is limited per IP and per IP+account (429 with
`Retry-After`), gallery unlock is limited per link.
- **Authorisation**: 26 `requireAdmin` checks cover the admin surface; missing or
disabled accounts are rejected; the desktop local owner is only used when
`LUMINARY_LOCAL=1`.
- **Gallery links**: separate password hash with its own salt, constant-time
compare, unlock cookie random per session and held in memory, so a restart
re-locks the gallery. Share tokens are 18 random bytes.
- **Bridge**: HMAC-SHA256 over the payload, version-tagged, expiry checked,
constant-time signature compare.
- **Path handling**: static requests are resolved then checked with
`path.relative` against `dist`; tether file names go through `basename` and
must match exactly; stored files are addressed by generated IDs.
- **Uploads**: `MAX_UPLOAD` enforced against `content-length` before reading and
again while streaming.
- **Headers**: CSP with `object-src 'none'`, `frame-ancestors 'self'`,
`nosniff`, `SAMEORIGIN`, `same-origin` referrer policy, restrictive
`Permissions-Policy`. No CORS headers are emitted, so browsers cannot read
responses cross-origin.
- **Secrets**: SMTP app password and bridge tokens are sealed with AES-256-GCM
(`server/secrets.mjs`); the key comes from `LUMINARY_SECRET_KEY` or a
`0600` file beside the database. No credentials or API keys are committed.
## Hardening opportunities (not vulnerabilities)
1. **CSP includes `'unsafe-eval'`.** It is there for the WebAssembly engines. The
modern token is `'wasm-unsafe-eval'`; keeping the broader one means any future
DOM-XSS can compile and run script. Tighten to `'wasm-unsafe-eval'` and test
LibRaw/JXL/ONNX still initialise.
2. **Server-side request forgery surface.** The Immich base URL and dashboard URL
are operator-supplied and fetched by the server with credentials attached.
An admin can point them at internal services. Acceptable for a self-hosted
tool, but worth blocking loopback/link-local targets by default, or stating
the trust assumption in the docs.
3. **Per-account sign-in limiting is scoped by IP.** A distributed attempt against
one address is not globally throttled; scrypt cost is the only brake. A global
per-account counter would close that.
4. **30-day sessions** with no rotation on privilege change. Revoking sessions on
password change is worth adding.
5. **No HSTS, no built-in TLS.** Correct for a loopback desktop app; for team
installs it depends on a reverse proxy, so document that.
6. **`secret.key` beside the database** protects backups and dumps, not a full
data-directory compromise. `LUMINARY_SECRET_KEY` is the stronger option and
should be recommended for team installs.
7. **Minimum password length is 8** with no breach-list check. Fine; consider 12
for admin accounts.
## Release artefact checks
- The desktop bundles copy `dist/` and production `node_modules/`; no dev
dependencies or test files are included.
- The new JPEG XL encoder is WebAssembly executed in the browser sandbox, loads
only when a JXL export is chosen, makes no network requests, and is Apache-2.0
(`@jsquash/jxl`, libjxl BSD-3-Clause). No new server-side attack surface.
- JPEG exports re-encode pixels, so camera EXIF is not carried into delivered
files; only the XMP block Luminary writes is added.
## Recommended order
1. `onnxruntime-node@1.31.1` with a denoise regression run (clears both production
highs).
2. Tighten CSP to `'wasm-unsafe-eval'` and re-test raw, JXL and denoise loading.
3. Vite/Vitest major upgrade on a branch (clears every dev advisory).
4. Seal the Immich API key if it is not already sealed.
5. Add `npm audit --omit=dev --audit-level=high` to `scripts/predeploy.mjs`.
Binary file not shown.
+4 -3
View File
@@ -255,7 +255,7 @@
<div class="qs-box"> <div class="qs-box">
<h2>6 · Deliver</h2> <h2>6 · Deliver</h2>
<ul> <ul>
<li><b>Export</b> → JPEG/PNG/WebP/TIFF, size, recipe, watermark.</li> <li><b>Export</b> → JPEG/PNG/WebP/JPEG XL/TIFF, size, recipe, watermark.</li>
<li><b>Share</b> → client gallery link with picks and comments.</li> <li><b>Share</b> → client gallery link with picks and comments.</li>
<li><b>Print</b> → A4/Letter/5×7 through the same renderer.</li> <li><b>Print</b> → A4/Letter/5×7 through the same renderer.</li>
</ul> </ul>
@@ -931,7 +931,7 @@
<table> <table>
<thead><tr><th style="width:26%">Option</th><th>What it does</th></tr></thead> <thead><tr><th style="width:26%">Option</th><th>What it does</th></tr></thead>
<tbody> <tbody>
<tr><td>Format</td><td>JPEG, PNG, WebP or uncompressed 16-bit TIFF. JPEG and WebP expose quality; PNG and TIFF are lossless.</td></tr> <tr><td>Format</td><td>JPEG, PNG, WebP, JPEG XL or uncompressed 16-bit TIFF. JPEG, WebP and JPEG XL expose quality; JPEG XL also has a lossless switch; PNG and TIFF are lossless.</td></tr>
<tr><td>Resize</td><td>Full resolution, a long-edge size in pixels, or a percentage of the cropped frame.</td></tr> <tr><td>Resize</td><td>Full resolution, a long-edge size in pixels, or a percentage of the cropped frame.</td></tr>
<tr><td>Quality</td><td>Encoder quality, 40–100. 90–95 is visually lossless for most photographs.</td></tr> <tr><td>Quality</td><td>Encoder quality, 40–100. 90–95 is visually lossless for most photographs.</td></tr>
<tr><td>File name</td><td>Template with <code>{name}</code>, <code>{date}</code>, <code>{time}</code> and <code>{index}</code>; the first result is previewed underneath.</td></tr> <tr><td>File name</td><td>Template with <code>{name}</code>, <code>{date}</code>, <code>{time}</code> and <code>{index}</code>; the first result is previewed underneath.</td></tr>
@@ -1215,7 +1215,8 @@
</table> </table>
<h2>Export formats</h2> <h2>Export formats</h2>
<p>JPEG, PNG, WebP and uncompressed 16-bit TIFF, at full resolution, a long edge, or a percentage of the cropped frame. Output dimensions always reflect the crop and rotation; colour space is sRGB, Display P3 or Adobe RGB with a generated ICC profile.</p> <p>JPEG, PNG, WebP, JPEG XL and uncompressed 16-bit TIFF, at full resolution, a long edge, or a percentage of the cropped frame. Output dimensions always reflect the crop and rotation; colour space is sRGB, Display P3 or Adobe RGB with a generated ICC profile.</p>
<p>JPEG XL is exported at 8-bit in sRGB, either lossy (quality 40–100) or lossless, using libjxl compiled to WebAssembly inside the app — the file is encoded on this computer and nothing is uploaded. There is no embedded ICC profile or XMP metadata in a JXL export yet; use JPEG or 16-bit TIFF when you need those. Chrome 155+, Firefox 158+ and Safari 17+ open .jxl files; Microsoft Edge does not display them yet.</p>
<h2>Badges on a card</h2> <h2>Badges on a card</h2>
<table> <table>
+16
View File
@@ -9,6 +9,7 @@
"version": "0.5.3.1", "version": "0.5.3.1",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jsquash/jxl": "^1.3.0",
"exifr": "^7.1.3", "exifr": "^7.1.3",
"libraw-wasm": "^1.6.0", "libraw-wasm": "^1.6.0",
"nodemailer": "^10.6.1", "nodemailer": "^10.6.1",
@@ -1259,6 +1260,15 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@jsquash/jxl": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@jsquash/jxl/-/jxl-1.3.0.tgz",
"integrity": "sha512-IVOPTneyOd9eBAuow+FnCYIP6wkIc7CjrCDnZGiqAPyJ63vMVxv3zoWiucGiZVh6u9vi/l40AkcS9QwkoVSAqA==",
"license": "Apache-2.0",
"dependencies": {
"wasm-feature-detect": "^1.5.1"
}
},
"node_modules/@rolldown/pluginutils": { "node_modules/@rolldown/pluginutils": {
"version": "1.0.0-beta.27", "version": "1.0.0-beta.27",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
@@ -3003,6 +3013,12 @@
} }
} }
}, },
"node_modules/wasm-feature-detect": {
"version": "1.10.1",
"resolved": "https://registry.npmjs.org/wasm-feature-detect/-/wasm-feature-detect-1.10.1.tgz",
"integrity": "sha512-+wz9+WpMKgQ7H1tm41nJbFwAvwX4DqY0jNY8Blw5Qe6hHg1yhCJ+AqU0R4lgX7p3pyo8irYIl1+mMNoBwSj2Zg==",
"license": "Apache-2.0"
},
"node_modules/why-is-node-running": { "node_modules/why-is-node-running": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+1
View File
@@ -21,6 +21,7 @@
"build:lens-db": "node scripts/build-lens-db.mjs" "build:lens-db": "node scripts/build-lens-db.mjs"
}, },
"dependencies": { "dependencies": {
"@jsquash/jxl": "^1.3.0",
"exifr": "^7.1.3", "exifr": "^7.1.3",
"libraw-wasm": "^1.6.0", "libraw-wasm": "^1.6.0",
"nodemailer": "^10.6.1", "nodemailer": "^10.6.1",
Binary file not shown.
+22 -3
View File
@@ -23,6 +23,7 @@ const FORMATS: { value: ExportFormat; label: string }[] = [
{ value: 'png', label: 'PNG (8-bit)' }, { value: 'png', label: 'PNG (8-bit)' },
{ value: 'webp', label: 'WebP' }, { value: 'webp', label: 'WebP' },
{ value: 'tiff16', label: 'TIFF (16-bit)' }, { value: 'tiff16', label: 'TIFF (16-bit)' },
{ value: 'jxl', label: 'JPEG XL' },
]; ];
/** /**
@@ -360,7 +361,7 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
)} )}
</div> </div>
{(opts.format === 'jpeg' || opts.format === 'webp') && ( {(opts.format === 'jpeg' || opts.format === 'webp' || opts.format === 'jxl') && (
<label className="field"> <label className="field">
<span>Quality · {opts.quality}</span> <span>Quality · {opts.quality}</span>
<input <input
@@ -369,11 +370,29 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
max={100} max={100}
value={opts.quality} value={opts.quality}
onChange={(e) => patch({ quality: Number(e.target.value) })} onChange={(e) => patch({ quality: Number(e.target.value) })}
disabled={busy} disabled={busy || (opts.format === 'jxl' && opts.jxlLossless === true)}
/> />
</label> </label>
)} )}
{opts.format === 'jxl' && (
<>
<label className="check-row">
<input
type="checkbox"
checked={opts.jxlLossless === true}
onChange={(e) => patch({ jxlLossless: e.target.checked })}
disabled={busy}
/>
Lossless — keeps every pixel and ignores the quality setting
</label>
<p className="muted small">
JPEG XL exports are 8-bit sRGB. Chrome, Firefox and Safari open them; Microsoft Edge
does not yet.
</p>
</>
)}
{sample && <ExportDetailStrip photo={sample} size={previewSize} />} {sample && <ExportDetailStrip photo={sample} size={previewSize} />}
<label className="field"> <label className="field">
@@ -478,7 +497,7 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
type="checkbox" type="checkbox"
checked={opts.embedProfile} checked={opts.embedProfile}
onChange={(e) => patch({ embedProfile: e.target.checked })} onChange={(e) => patch({ embedProfile: e.target.checked })}
disabled={opts.format === 'webp' || opts.format === 'png'} disabled={opts.format === 'webp' || opts.format === 'png' || opts.format === 'jxl'}
/> />
Embed {COLOR_SPACE_OPTIONS.find((option) => option.value === (opts.colorSpace ?? 'srgb'))?.label ?? 'sRGB'} profile (JPEG/TIFF) Embed {COLOR_SPACE_OPTIONS.find((option) => option.value === (opts.colorSpace ?? 'srgb'))?.label ?? 'sRGB'} profile (JPEG/TIFF)
</label> </label>
+8
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { outputSize } from '../gl/renderer'; import { outputSize } from '../gl/renderer';
import { defaultEdits } from './edits'; import { defaultEdits } from './edits';
import { buildFileName, DEFAULT_EXPORT } from './export';
import type { PhotoRecord } from '../types';
describe('export output dimensions', () => { describe('export output dimensions', () => {
it('matches the source for an uncropped image', () => { it('matches the source for an uncropped image', () => {
@@ -19,6 +21,12 @@ describe('export output dimensions', () => {
expect(outputSize(edits, 4000, 3000)).toEqual({ w: 4950, h: 4950 }); expect(outputSize(edits, 4000, 3000)).toEqual({ w: 4950, h: 4950 });
}); });
it('writes the JPEG XL extension for a JXL export', () => {
const photo = { name: 'DSCF1234.RAF', addedAt: Date.now() } as PhotoRecord;
const name = buildFileName('{name}', photo, 0, { ...DEFAULT_EXPORT, format: 'jxl' });
expect(name).toBe('DSCF1234.jxl');
});
it('applies the crop after the rotated frame is calculated', () => { it('applies the crop after the rotated frame is calculated', () => {
const edits = defaultEdits(); const edits = defaultEdits();
edits.crop.angle = 45; edits.crop.angle = 45;
+27 -1
View File
@@ -8,8 +8,9 @@ import { createZipBlob, zipFileName } from './zip';
import { profileFor, type OutputColorSpace } from './icc'; import { profileFor, type OutputColorSpace } from './icc';
import { convertFloatPixels, convertImageData } from './colorSpace'; import { convertFloatPixels, convertImageData } from './colorSpace';
import { encodeTiff16 } from './tiff'; import { encodeTiff16 } from './tiff';
import { encodeJxl } from './jxl';
export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16'; export type ExportFormat = 'jpeg' | 'png' | 'webp' | 'tiff16' | 'jxl';
export type ResizeMode = 'none' | 'longEdge' | 'percent'; export type ResizeMode = 'none' | 'longEdge' | 'percent';
export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center'; export type WatermarkPosition = 'br' | 'bl' | 'tr' | 'tl' | 'center';
@@ -27,6 +28,8 @@ export interface ExportOptions {
zip: boolean; zip: boolean;
/** Extra capture sharpening applied only to the exported pixels. */ /** Extra capture sharpening applied only to the exported pixels. */
outputSharpen: number; outputSharpen: number;
/** JPEG XL only: keep every pixel instead of using the quality slider. */
jxlLossless?: boolean;
/** Write title/caption/creator/copyright/keywords into the file. */ /** Write title/caption/creator/copyright/keywords into the file. */
metadata: boolean; metadata: boolean;
/** Embed the generated sRGB ICC profile in JPEG/TIFF files. */ /** Embed the generated sRGB ICC profile in JPEG/TIFF files. */
@@ -56,6 +59,7 @@ export const DEFAULT_EXPORT: ExportOptions = {
nameTemplate: '{name}', nameTemplate: '{name}',
zip: true, zip: true,
outputSharpen: 0, outputSharpen: 0,
jxlLossless: false,
metadata: true, metadata: true,
embedProfile: true, embedProfile: true,
watermark: { enabled: false, text: '', position: 'br', opacity: 55, size: 4 }, watermark: { enabled: false, text: '', position: 'br', opacity: 55, size: 4 },
@@ -66,6 +70,7 @@ const MIME: Record<ExportFormat, string> = {
png: 'image/png', png: 'image/png',
webp: 'image/webp', webp: 'image/webp',
tiff16: 'image/tiff', tiff16: 'image/tiff',
jxl: 'image/jxl',
}; };
const EXT: Record<ExportFormat, string> = { const EXT: Record<ExportFormat, string> = {
@@ -73,6 +78,7 @@ const EXT: Record<ExportFormat, string> = {
png: 'png', png: 'png',
webp: 'webp', webp: 'webp',
tiff16: 'tif', tiff16: 'tif',
jxl: 'jxl',
}; };
function download(blob: Blob, filename: string) { function download(blob: Blob, filename: string) {
@@ -178,6 +184,12 @@ export async function renderPhotoBlob(
if (opts.watermark.enabled && opts.watermark.text.trim()) { if (opts.watermark.enabled && opts.watermark.text.trim()) {
output = paintWatermark(output, photo, opts); output = paintWatermark(output, photo, opts);
} }
if (opts.format === 'jxl') {
return encodeJxl(readPixels(output), {
quality: opts.quality,
lossless: opts.jxlLossless === true,
});
}
const mime = MIME[opts.format]; const mime = MIME[opts.format];
let blob = await new Promise<Blob | null>((resolve) => let blob = await new Promise<Blob | null>((resolve) =>
output.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))), output.toBlob(resolve, mime, Math.min(1, Math.max(0.1, opts.quality / 100))),
@@ -197,6 +209,20 @@ export async function renderPhotoBlob(
} }
} }
/**
* The render canvas holds a WebGL context, so its pixels have to be drawn into
* a 2D canvas before an encoder can read them.
*/
function readPixels(source: HTMLCanvasElement): ImageData {
const canvas = document.createElement('canvas');
canvas.width = source.width;
canvas.height = source.height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) throw new Error('Could not read the export pixels');
ctx.drawImage(source, 0, 0);
return ctx.getImageData(0, 0, canvas.width, canvas.height);
}
function convertCanvas(source: HTMLCanvasElement, space: OutputColorSpace) { function convertCanvas(source: HTMLCanvasElement, space: OutputColorSpace) {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
canvas.width = source.width; canvas.width = source.width;
+82
View File
@@ -0,0 +1,82 @@
/**
* JPEG XL export (8-bit sRGB), encoded by libjxl compiled to WebAssembly.
*
* The codec is imported on demand: it is roughly 1.4 MB of wasm plus glue, and
* most sessions never export a JXL. Only the single-threaded build is used —
* the app is not cross-origin isolated, so the multithreaded glue would fall
* back anyway, and its worker entry points cannot be bundled.
*
* The glue resolves its wasm relative to its own module URL, which a bundler
* rewrites; `locateFile` points it at the URL Vite actually emitted.
*/
import jxlWasm from '@jsquash/jxl/codec/enc/jxl_enc.wasm?url';
export interface JxlOptions {
/** 1–100, the same number the modal's quality slider shows. */
quality: number;
lossless: boolean;
}
interface JxlEncodeOptions {
effort: number;
quality: number;
lossless: boolean;
progressive: boolean;
epf: number;
lossyPalette: boolean;
decodingSpeedTier: number;
photonNoiseIso: number;
lossyModular: boolean;
}
interface JxlModule {
encode(data: BufferSource, width: number, height: number, options: JxlEncodeOptions): Uint8Array | null;
}
let encoder: Promise<JxlModule> | null = null;
function loadEncoder(): Promise<JxlModule> {
if (!encoder) {
encoder = (async () => {
const [{ default: factory }, { initEmscriptenModule }] = await Promise.all([
import('@jsquash/jxl/codec/enc/jxl_enc.js'),
import('@jsquash/jxl/utils.js'),
]);
const module = await initEmscriptenModule(factory as never, undefined, {
locateFile: (path: string) => (path.endsWith('jxl_enc.wasm') ? jxlWasm : path),
});
return module as unknown as JxlModule;
})().catch((error) => {
// A failed load must not poison every later export.
encoder = null;
throw error;
});
}
return encoder;
}
export async function encodeJxl(image: ImageData, options: JxlOptions): Promise<Blob> {
const module = await loadEncoder();
const lossless = options.lossless === true;
const quality = Math.min(100, Math.max(1, Math.round(options.quality || 90)));
const result = module.encode(image.data, image.width, image.height, {
quality: lossless ? 100 : quality,
lossless,
// libjxl defaults to effort 7, which is a long wait single-threaded on a
// 45 MP frame. 5 keeps a batch moving and costs little for photographs.
effort: 5,
progressive: false,
epf: -1,
lossyPalette: false,
decodingSpeedTier: 0,
photonNoiseIso: 0,
lossyModular: false,
});
if (!result || !result.byteLength) throw new Error('JPEG XL encoding failed');
// A fresh buffer: the encoder returns a view that may over-allocate, and a
// Blob must not keep the wasm heap alive.
const bytes = new Uint8Array(result.byteLength);
bytes.set(result);
return new Blob([bytes], { type: 'image/jxl' });
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />