This is a simple Svelte image component that uses Sharp to automatically optimize images during runtime. It can resize, crop, and convert images to different formats.
GitHub NPMCreate a new api route at /routes/api/image/+server.ts with the
following code:
import { optimizeImage } from "svelte-sharp-image/server"; import type { RequestHandler } from "@sveltejs/kit"; export const GET: RequestHandler = async ({ url }) => { return await optimizeImage(url); };
You can also pass in a config object into the optimizeImage function.
export type ImageOptimizeConfig = { getCache?: (tag: string) => Promise<Buffer | undefined>; saveCache?: (tag: string, buffer: Buffer) => Promise<void>; safeEndpoints?: string[]; }
Then use the Image component from the library.
<Image src="https://i.mrxbox98.me/file/2024/08/chrome_Sb3dUdhQfy.png" style="width: 200px" /> <Image src="/favicon.png" /> <Image src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/AJ_Digital_Camera.svg" />
Yields the following result:
You can view the source of the images to check the format and compression.
The Image component simply extends the base html img, so all props that work on img will also work and affect Image. This includes class, style etc...
If you like this tool, consider staring the repo:
Star