Leptos Image

Crates.io docs.rs

Crafted with inspiration from Next.js

Images make a substantial impact on the size and performance of a website, so why not get them right?

Enter Leptos <Image/>, a component that enhances the standard HTML <img> element with automatic image optimization features.

Installation

Add leptos_image via cargo:

bash cargo add leptos_image

Add the SSR Feature under [features] in your Cargo.toml

toml [features] ssr = [ "leptos_image/ssr", # ... ]

Quick Start

REQUIRES SSR + AXUM

Go to your SSR Main Function in main.rs

Before you create your router, call the cache_app_images function with the project root. This will cache all the images in your app, and generate the LQIPs.

If you have a lot of images, then you should probably only call this function in production because it will delay your server startup.

If you don't include this function, then image caching will happen at runtime.

```rust

use leptos::; use leptos_image::;

let conf = getconfiguration(None).await.unwrap(); let leptosoptions = conf.leptosoptions; let root = leptosoptions.site_root.clone();

use leptosimage::cache::cacheapp_images;

cacheappimages(root, |cx: Scope| view! {cx, }, 2, || (), || ()) .await .expect("Failed to cache images");

```

Next add an endpoint to your router that serves the cached images. For now, the endpoint path must be /cache/image and is not configurable

```rust

use axum::{routing::{get, post}, Router};

let router = ...

router.route("/cache/image", get(imagecachehandler));

```

Next inside of leptos_routes, call the provide_image_context function. This will provide the Image Context to your App during SSR.

The final router should look something like this!

```rust

let router = Router::new() .route("/api/*fnname", post(leptosaxum::handleserverfns)) .leptosroutes(&leptosoptions, routes, |cx| { // Image Context is provided here! provideimagecontext(cx); view! { cx, } }) // Here's the new route! .route("/cache/image", get(imagecachehandler)) .withstate(leptosoptions);

```

Now you can use the Image Component anywhere in your app!

```rust

[component]

pub fn MyPage(cx: Scope) -> impl IntoView { view! { cx, <Image src="/cute_ferris.png" blur=true width=750 height=500 quality=85 /> } } ```</p> <p>And that's it. You're all set to use the Image Component.</p> <h2>Caveats:</h2> <ul> <li>Images will only be retrieved from routes that are non-dynamic (meaning not <code>api/post/:id</code> in Route path).</li> <li>Images can take a few seconds to optimize, meaning first startup of server will be slower.</li> <li>Actix Support is coming soon!</li> </ul> </body></html>