Skip to main content

Crate larust_image

Crate larust_image 

Source
Expand description

Automatic image optimization - Larust’s answer to Next.js’s <Image /> component. Core framework surface, not an optional Tier-1 shim - the same tier as @wire/@resource/@spa/@vitex, always compiled in, never behind a Cargo feature flag, because the <Image ...> template tag itself (larust-view’s own parser, see that crate’s ast.rs) is real, fixed grammar, not something an optional crate bolts on.

Local images only, for now. ImageOptions::src is always a path relative to the app’s own public/ directory - never an arbitrary remote URL. Proxying remote images the way Next.js’s own allow-listed images.domains config does is a real, separate feature (SSRF hardening, fetch timeouts/size limits, a domain allow-list) - a deliberate v1 boundary, not an oversight.

§What actually happens

  1. tag (called by <Image ...> - see larust-macros’ own view! codegen) is a pure, synchronous computation: it builds a plain <img> pointing at optimized_url’s URL. No decoding, resizing, or encoding happens yet.
  2. The browser requests that URL, handled by route::ImagePlugin’s one route. The first request for a given combination of inputs decodes the source file, resizes it, encodes it, and writes the result to storage/framework/cache/images/ before serving it.
  3. Every later request for that same combination is a plain cached-file read - no re-decoding, no re-encoding.

§Formats

AVIF (via ravif/rav1e, both pure Rust - no C toolchain, matching this project’s own redb posture elsewhere) when the request’s Accept header includes image/avif; otherwise lossy WebP (via webpkit, also pure Rust) when Accept includes image/webp; JPEG as the universal fallback when neither is accepted, or if the preferred encoder fails for any reason.

{: .note } WebP support is honest, not aspirational. webpkit is a genuine, pure-Rust lossy VP8 encoder - no libwebp/C dependency, matching this crate’s AVIF posture - but it’s pre-1.0 upstream, with no published conformance or benchmark results yet, unlike ravif’s own AVIF path. It was picked over the more feature-complete zenwebp for a license reason, not a maturity one: zenwebp 0.3.0+ is AGPL-3.0/paid- commercial, which this Apache-2.0, always-compiled-in crate can never depend on. Every lossy WebP encode that fails falls back to JPEG automatically (the same safety net AVIF already has) - a WebP bug degrades an image’s compression, never breaks the page.

§Attributes

Every ImageOptions field maps to one <Image ...> attribute (see docs/MACROS.md’s own entry for the exact template-level grammar):

  • width/height - a fixed box; resized to exactly this, not aspect-ratio-preserving. Required unless fill is set.
  • fill - expands to fill the parent element instead of a fixed box (position:absolute;inset:0;object-fit:cover - the parent needs its own position: relative/absolute/fixed). Mutually exclusive with width/height - larust-macros’ own codegen rejects both being given together at compile time.
  • sizes - a CSS-like breakpoint hint ("(max-width: 768px) 100vw, 50vw"), passed straight through to the rendered sizes attribute. Its presence is also what triggers build_srcset - there’s no separate srcset attribute to write by hand; every variant it names is generated on demand (decoded/resized/encoded, then cached) the first time some visitor’s browser actually requests it, exactly like the single base image already is. See [SRCSET_BREAKPOINTS].
  • priority - loading="eager" + fetchpriority="high", for an LCP element (a hero image), plus a real resource hint: an inline <link rel="preload" as="image"> immediately before the <img> itself (not injected into <head> - see tag’s own doc comment for why inline placement gets essentially the same preload timing as a <head>-placed one would for a response this framework always serves as one complete buffer, never streamed).
  • loading - "lazy" (default) or "eager", overridden to "eager" automatically when priority is set.
  • quality - 1-100, defaults to DEFAULT_QUALITY.
  • placeholder - Empty (default) or Blur, a background-image blur-up shown behind the real <img> while it loads. See [route]’s own doc comment for why this is a cached, separately generated thumbnail rather than Next.js’s build-time-computed inline base64 - and why a brand-new image’s very first view renders with no blur.
  • unoptimized - serves src exactly as-is, skipping the optimize route entirely. For the cases this crate’s own processing would actively break: an SVG (not a raster format image can decode as a bitmap at all), an animated GIF (resize/re-encode would collapse it to one frame), or a already-tiny icon not worth a round trip to optimize.

Re-exported through larust_support::image (unconditionally - see crates/larust-support/src/lib.rs) so generated apps depend only on larust-support, never on this crate directly.

§Deliberately out of scope

  • Remote images. See this module’s own opening paragraph.
  • Static-import-time (build-time) optimization. Everything here is on-demand, at request time, cached after the first hit - there’s no separate build step that pre-generates optimized variants.
  • Any object-fit mode besides cover for fill. A real, small follow-up (an object_fit option) if a caller ever needs contain/fill/none; not built speculatively ahead of that need.

Structs§

ImageOptions
Every <Image ...> attribute, one field each - see this crate’s own doc comment for the full meaning of each one. Owned Strings, not borrowed &strs, deliberately: larust-macros’ own codegen (which constructs this struct literal directly, one field per attribute, no builder calls needed there) hands it a :src="expr" dynamic attribute’s own value exactly as whatever type that expression produces (String, &str, anything Display) - converted uniformly via .to_string() either way - rather than needing a lifetime parameter here just to borrow a value that’s just as often a literal as it is some other owned value computed on the spot. ImageOptions::new/ImageOptions::fill plus the builder-style setters below are for a hand-written Rust call site instead, and accept impl Into<String> so a plain &str literal still needs no extra ceremony there either.
ImagePlugin
OptimizeResult
optimize’s full result - the main resized/encoded image, plus (when asked for) a tiny blurred thumbnail generated from the same decode, so producing one never costs a second, separate decode of the source file. See [crate::route]’s own doc comment for why the blur thumbnail is generated here, as a side effect of an ordinary optimize request, rather than computed synchronously inside crate::tag.
Optimized

Enums§

EncodedFormat
Which format optimize actually produced - the caller needs this to pick the right Content-Type/cache file extension, since it depends on the request’s own Accept header, not just the input.
FormatPreference
Which format optimize should try first, decided by the caller from the request’s own Accept header - Avif wins over Webp when both are accepted (the ordinary case: a browser that accepts AVIF almost always lists it ahead of WebP in Accept, and AVIF compresses better at equal quality). Each lossy tier falls back to EncodedFormat::Jpeg on a real encode failure - see optimize’s own match arm for why that’s always safe to do silently.
Loading
"lazy" (default - load when entering the viewport) or "eager" (load immediately). See ImageOptions::loading.
OptimizeError
Placeholder
Empty (default - nothing shown while loading) or Blur (a cached blur-up thumbnail behind the image). See ImageOptions::placeholder.
ResizeTarget
How to resize the decoded source - see optimize’s own doc comment for when each is used.

Constants§

DEFAULT_QUALITY
Default JPEG/AVIF quality (1-100) when a call site doesn’t pick one - the same ballpark Next.js’s own default (75) uses: a real size reduction with no visible artifacting for typical photographic content.
MAX_DIMENSION
A conservative upper bound on any single dimension - not a real product limit, just a guard against a request accidentally (or maliciously) asking this crate to allocate and encode an enormous image. Four times a typical high-DPI viewport’s own largest dimension is generous for every real layout this crate is meant to serve.

Functions§

build_srcset
srcset’s own value when sizes is set - one entry per [SRCSET_BREAKPOINTS] (capped at MAX_DIMENSION), each an aspect-ratio-preserving width-only variant (see optimized_url’s own height: None case) of the same on-demand route the plain src already uses - nothing here is pre-generated; a given breakpoint is decoded/resized/encoded (and cached) only the first time some visitor’s browser actually requests exactly that width.
optimize
Decodes source once, resizes it per target for the main result - preferred_format (the caller decides this from the request’s own Accept header) when that format’s own encoder succeeds, JPEG otherwise - and, when generate_blur is set, also produces a tiny blurred-placeholder thumbnail from the same decode (always JPEG, regardless of preferred_format - it’s consumed directly by the browser’s own CSS decoder as an inline data URI, never served as a standalone resource a format negotiation could apply to).
optimized_url
The URL <Image ...> renders into its src attribute (or one entry of its srcset) - your own app never calls this route directly, this is the one real entry point. src is a path relative to public/ (e.g. "images/hero.jpg" for a file at public/images/hero.jpg) - percent-encoded here so a path containing spaces or other reserved query-string characters still round-trips correctly. height: None requests an aspect-ratio-preserving resize instead of a fixed box (see ResizeTarget::Width) - used for every fill/sizes-driven variant, where only a target width is actually known.
tag
A ready <img> tag - what <Image ...> actually expands to. See this crate’s own doc comment for the full meaning of every ImageOptions field. Takes options by reference - several fields (src in particular) are read more than once below, and ImageOptions owns Strings rather than borrowing &strs (see that struct’s own doc comment for why), so a by-value ImageOptions would mean the first read moved a field a later one still needed.