### Install imagetools-core Source: https://github.com/jonaskruckenberg/imagetools/blob/main/packages/core/README.md Install the imagetools-core package using npm. ```bash npm install imagetools-core ``` -------------------------------- ### Project Folder Structure Source: https://github.com/jonaskruckenberg/imagetools/blob/main/CONTRIBUTING.md Overview of the monorepo's directory structure, including docs, examples, and packages. ```tree ┠─ docs: ┃ Documentation that is common to all packages. ┃ ┠─ examples: ┃ Example projects showing the real-word usage of imagetools. ┃ ┖─ packages ┠─ core: ┃ Holds all transforms and common utility functions needed for builtools integrations. ┃ ┖─ vite: The integration with the vite frontend builtool. ``` -------------------------------- ### Load, Generate, and Apply Image Transforms Source: https://github.com/jonaskruckenberg/imagetools/blob/main/packages/core/README.md Load an image, generate transformation configurations, and apply them using imagetools-core. Ensure sharp is installed for transformations. ```javascript import { loadImage, applyTransforms, builtins, generateTransforms } from 'imagetools-core' // loadImageFromDisk is a utility function that creates a sharp instances of the specified image const image = loadImage('./example.jpg') // our image configuration const config = { width: '400', height: '300', format: 'webp' } // This function takes our config and an array of transformFactories and creates an array of transforms // the resulting array of transforms can be cached const { transforms, warnings } = generateTransforms(config, builtins) // apply the transforms and transform the given image const { image: transformedImage, metadata } = await applyTransforms(transforms, image) transformedImage // a sharp instance of the transformed image metadata // the image metadata produced by the transforms ``` -------------------------------- ### Custom Config Resolution with Presets Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/guide/extending.md Implement custom image configuration resolution by passing a function to the `resolveConfigs` plugin option. This example shows how to create presets for site-specific image widths and formats. ```typescript const defaultPresets = { default: {widths: [300, 800, 1200]} } export function resolveConfigsWithPresets(pluginConfig) { // use provided presets or use defaults above const presets = pluginConfig?.presets || defaultPresets // this is the custom resolveConfigs function return function (config) { // look for 'mysite' in the import name const mysite_config = config.find(([key]) => key === "mysite") if (mysite_config) { // get the preset if specified const [, [value]] = mysite_config // see if there is a custom preset specified, eg: mysite=mypreset, or use default const preset_name = value.trim().length ? value.trim() : "default" // fall back to default preset if one given doesn't exist const preset = presets[preset_name] || defaultPresets.default // map preset widths to const widths = preset.widths return widths.map((width, index) => ({ width, webp: "" })); } // else return undefined and default resolveConfigs will be called } } ``` ```javascript // vite.config.js, etc ... plugins: [ react(), imagetools({ resolveConfigs: resolveConfigsWithPresets({ mypreset: {widths: [100,200,300]} }) }) ] ... ``` ```typescript // page.tsx, etc import img_urls from "./myimage.png?mypreset" ``` -------------------------------- ### Default directives with a function Source: https://github.com/jonaskruckenberg/imagetools/blob/main/packages/vite/README.md Configure default directives using a function that inspects the URL. This example applies a 'tint' directive if the 'spotify' query parameter is present. ```javascript import { defineConfig } from 'vite' import { imagetools } from 'vite-imagetools' export default defineConfig({ plugins: [ imagetools({ defaultDirectives: (url) => { if (url.searchParams.has('spotify')) { return new URLSearchParams({ tint: 'ffaa22' }) } return new URLSearchParams() } }) ] }) ``` -------------------------------- ### Override Config Resolution with Custom Presets Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Customize how URL parameters are mapped to ImageConfig arrays to enable shorthand presets. This example defines 'hero' and 'thumbnail' presets that expand into multiple image configurations. ```typescript // vite.config.ts import { defineConfig } from 'vite' import { imagetools, resolveConfigs } from 'vite-imagetools' import type { ResolveConfigs } from 'vite-imagetools' const presets: Record = { hero: { widths: [800, 1200, 1600], format: 'webp' }, thumbnail: { widths: [100, 200], format: 'webp' }, } const customResolve: ResolveConfigs = (entries, outputFormats) => { const presetEntry = entries.find(([k]) => k === 'preset') if (presetEntry) { const presetName = presetEntry[1][0] const preset = presets[presetName] ?? presets.hero return preset.widths.map((w) => ({ w: String(w), format: preset.format })) } // Fall back to default resolution return resolveConfigs(entries, outputFormats) } export default defineConfig({ plugins: [imagetools({ resolveConfigs: customResolve })] }) // Usage: import heroImages from './banner.jpg?preset=hero&as=srcset' ``` -------------------------------- ### Install vite-imagetools via npm Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/install.md Install the vite-imagetools package as a development dependency for your Vite project. ```bash npm install --save-dev vite-imagetools ``` -------------------------------- ### Define Custom Output Format Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Extend the `as=…` mechanism by adding a custom `OutputFormat` function to `extendOutputFormats`. This example defines a 'blurhash' format that returns image metadata including a placeholder blurhash. ```typescript // vite.config.ts import { defineConfig } from 'vite' import { imagetools } from 'vite-imagetools' import type { OutputFormat } from 'imagetools-core' // Custom format: as=blurhash — returns { src, blurhash } (illustrative) const blurhashFormat: OutputFormat = (_args) => (metadatas) => { const largest = metadatas.reduce((a, b) => ((a.width ?? 0) > (b.width ?? 0) ? a : b)) return { src: largest.src, width: largest.width, height: largest.height, // In a real implementation you'd compute the actual blurhash here placeholder: 'LKO2?U%2Tw=w]~RBVZRi};RPxuwH' } } export default defineConfig({ plugins: [ imagetools({ extendOutputFormats: (builtins) => ({ ...builtins, blurhash: blurhashFormat }) }) ] }) // Usage: import data from './photo.jpg?w=800&format=webp&as=blurhash' // data === { src: '...', width: 800, height: 533, placeholder: 'LKO2?...' } ``` -------------------------------- ### Get Image URL Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/directives.md Returns a direct URL to the generated image. This is the default behavior when only one output image is produced. ```javascript import Image from 'example.jpg?w=500' // the type of Image is a string and it's a URL to the transformed image ``` -------------------------------- ### Import and Resize Image with imagetools Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/why.md Use this syntax to import an image and specify its desired width and height. imagetools will handle the resizing automatically. ```javascript import Image from 'example.jpeg?w=300&h=400' ``` -------------------------------- ### Choose Output Format with `as` Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Control the JavaScript value returned by the image import. Options include a default URL string, srcset string, image object, picture object, or metadata object. ```javascript // Default: single URL string import src from './photo.jpg?w=800&format=webp' // src === '/assets/photo.abc123.webp' ``` ```javascript // srcset string for use in / import avifSrcset from './photo.jpg?w=400;800;1200&format=avif&as=srcset' import webpSrcset from './photo.jpg?w=400;800;1200&format=webp&as=srcset' import fallback from './photo.jpg?w=800' // Usage: const html = ` ` ``` ```javascript // img object (best src + optional srcset) import img from './photo.jpg?w=400;800&format=webp&as=img' // img === { src: '...800w.webp', w: 800, h: 533, srcset: '...400w 400w, ...800w 800w' } ``` ```javascript // picture object (all formats + fallback) import picture from './photo.jpg?w=400;800&format=avif;webp;jpg&as=picture' // picture.sources === { 'image/avif': '400w ..., 800w ...', 'image/webp': '...' } // picture.img === { src: '...800.jpg', w: 800, h: 533 } ``` ```javascript // metadata object (all fields) import meta from './photo.jpg?w=600&format=webp&as=metadata' // meta === { src: '...', width: 600, height: 400, format: 'webp', ... } ``` ```javascript // metadata whitelist — only import selected keys (smaller bundle) import { width, format } from './photo.jpg?w=600&format=webp&as=meta:width;format' ``` -------------------------------- ### Advanced Resize Control with `fit`, `position`, `kernel` Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Fine-tune resize behavior when both `w` and `h` are specified. Control fitting strategies, cropping position, and interpolation kernel for resize quality. ```javascript // fit strategies: cover (default) | contain | fill | inside | outside import coverImg from './photo.jpg?w=400&h=300&fit=cover' import containImg from './photo.jpg?w=400&h=300&fit=contain&background=white' ``` ```javascript // position within cover/contain crop import topCrop from './photo.jpg?w=400&h=300&fit=cover&position=top' import attentionCrop from './photo.jpg?w=400&h=300&fit=cover&position=attention' ``` ```javascript // interpolation kernel for resize quality // nearest | cubic | mitchell | lanczos2 | lanczos3 import sharp from './photo.jpg?w=200&kernel=lanczos3' ``` -------------------------------- ### Configure Caching Directory and Enable Caching Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/caching.md Enable caching and specify a custom directory for storing cached images. Caching is enabled by default. ```javascript // vite.config.js, etc ... plugins: [ react(), imagetools({ cache: { enabled: true, dir: './node_modules/.cache/imagetools' } }) ] ... ``` -------------------------------- ### Define a Custom Directive in TypeScript Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/guide/extending.md A directive is a factory function that accepts configuration and context, returning an ImageTransformation or undefined. This example shows how to create a custom directive that reuses existing directives for resizing and formatting. ```typescript type TransformFactory = ( metadata: Partial, ctx: TransformFactoryContext ) => ImageTransformation | undefined ``` -------------------------------- ### Define a Custom Directive in TypeScript Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/extending.md Define a custom directive factory function that takes configuration and context, returning an ImageTransformation or undefined. This example shows how to reuse existing directives like resize and format. ```typescript import { resize, format } from 'imagetools' function customDirective(config, ctx) { // we would like to reuse the existing directives as much as possible const resizeTransform = resize({ w: config.customKeyword }, ctx) const formatTransform = format({ format: 'webp' }, ctx) if (!resizeTransform) return // return the transform function return function customTransform(image) { // apply both transformations and return the result return formatTransform(resizeTransform(image)) } } ``` -------------------------------- ### resolveConfigs Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/functions/resolveConfigs.md Builds all possible combinations of entries and output formats to create image configurations. ```APIDOC ## Function: resolveConfigs() > **resolveConfigs**(`entries`, `outputFormats`): `ImageConfig`[] Defined in: packages/core/dist/lib/resolve-configs.d.ts:8 This function builds up all possible combinations the given entries can be combined and returns it as an array of objects that can be given to a the transforms. ### Parameters #### entries * `string` | `string`[] | `Array` The url parameter entries #### outputFormats * `Record` ## Returns * `ImageConfig`[] An array of directive options ``` -------------------------------- ### Add Custom TransformFactory Directive Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Define a custom TransformFactory to add new directives, such as generating responsive images. Return `undefined` if the directive is not present, or a transformation function if it applies. This example shows how to create a '?responsive' directive. ```typescript // vite.config.ts import { defineConfig } from 'vite' import { imagetools, resize, format } from 'vite-imagetools' import type { TransformFactory } from 'imagetools-core' // Custom directive: ?responsive — produces 400w/800w/1200w WebP images const responsiveDirective: TransformFactory = (config, ctx) => { if (!('responsive' in config)) return undefined ctx.useParam('responsive') // mark param as consumed (suppresses warnings) const resizeSmall = resize({ w: '400' }, ctx) const resizeMedium = resize({ w: '800' }, ctx) const resizeLarge = resize({ w: '1200' }, ctx) const toWebp = format({ format: 'webp' }, ctx) return async (image) => { // Custom factories typically produce ONE image per config. // For generating multiple sizes, use resolveConfigs instead. return toWebp(resizeMedium ? resizeMedium(image) : image) } } export default defineConfig({ plugins: [ imagetools({ extendTransforms: (builtins) => [...builtins, responsiveDirective] }) ] }) // Usage in component: // import img from './photo.jpg?responsive&as=img' ``` -------------------------------- ### Generate AVIF and WebP Srcsets Source: https://github.com/jonaskruckenberg/imagetools/blob/main/examples/vite-simple/README.md Import dynamically generated AVIF and WebP image sources with specified widths and srcset output. This is useful for creating responsive images that adapt to different screen sizes and browser capabilities. ```typescript import srcsetAvif from '../example.jpg?w=500;700;900;1200&format=avif&as=srcset' import srcsetWebp from '../example.jpg?w=500;700;900;1200&format=webp&as=srcset' ``` -------------------------------- ### resolveConfigs() Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/functions/resolveConfigs.md Builds up all possible combinations of entries and output formats to create an array of ImageConfig objects for transformations. ```APIDOC ## Function: resolveConfigs() > **resolveConfigs**(`entries`, `outputFormats`): `ImageConfig`[] Defined in: [packages/core/src/lib/resolve-configs.ts:17](https://github.com/JonasKruckenberg/imagetools/blob/aa84664d044e4b733cdf7005c6730584bc92ec90/packages/core/src/lib/resolve-configs.ts#L17) This function builds up all possible combinations the given entries can be combined and returns it as an array of objects that can be given to a the transforms. ### Parameters #### entries - `entries` (["string", "string"[]][]): The url parameter entries #### outputFormats - `outputFormats` (`Record` <`string`, [`OutputFormat`](../type-aliases/OutputFormat.md) ### Returns - `ImageConfig`[]: An array of directive options ``` -------------------------------- ### generateTransforms(config, factories, searchParams, logger?) Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Builds a transform pipeline by instantiating ImageTransformation functions based on a given ImageConfig and a list of TransformFactory functions. ```APIDOC ## generateTransforms(config, factories, searchParams, logger?) ### Description Given a single `ImageConfig` and an array of `TransformFactory` functions, instantiates a list of `ImageTransformation` functions ready to be applied to a sharp instance. ### Parameters #### Path Parameters - **config** (ImageConfig) - Required - The image configuration object. - **factories** (Array) - Required - An array of transform factory functions. - **searchParams** (URLSearchParams) - Required - The URLSearchParams object. - **logger** (object) - Optional - An object with `info`, `warn`, and `error` methods for logging. ### Request Example ```ts import sharp from 'sharp' import { generateTransforms, builtins, parseURL, resolveConfigs, builtinOutputFormats, extractEntries } from 'imagetools-core' const url = parseURL('/img.jpg?w=800&format=webp&quality=85') const entries = extractEntries(url.searchParams) const [config] = resolveConfigs(entries, builtinOutputFormats) const { transforms, parametersUsed } = generateTransforms( config, builtins, url.searchParams, { info: console.log, warn: console.warn, error: console.error } ) console.log(parametersUsed) // Set { 'w', 'format', 'quality' } ``` ``` -------------------------------- ### ResizeOptions Properties Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/interfaces/ResizeOptions.md This interface outlines the properties that can be used to configure image resizing operations. Users can specify width, height, aspect ratio, and whether to allow upscaling. ```APIDOC ## Interface: ResizeOptions ### Description Defines the configuration options for resizing an image. ### Properties #### `w` (string) - **Description**: Width in pixels. - **Defined in**: packages/core/dist/transforms/resize.d.ts:4 #### `h` (string) - **Description**: Height in pixels. - **Defined in**: packages/core/dist/transforms/resize.d.ts:6 #### `aspect` (string) - **Description**: Aspect ratio of the image. - **Defined in**: packages/core/dist/transforms/resize.d.ts:8 #### `allowUpscale` (string | "true") - **Description**: Whether to allow making images larger. Defaults to false. - **Defined in**: packages/core/dist/transforms/resize.d.ts:10 #### `basePixels` (string) - **Description**: The width in pixels for the 1x pixel density descriptor. If supplied, output will use pixel density descriptors rather than width descriptors. - **Defined in**: packages/core/dist/transforms/resize.d.ts:15 ``` -------------------------------- ### Generate Image Transformation Pipeline Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Builds a list of ImageTransformation functions for a sharp instance based on a configuration and available transform factories. Logs used parameters. ```typescript import sharp from 'sharp' import { generateTransforms, builtins, parseURL, resolveConfigs, builtinOutputFormats, extractEntries } from 'imagetools-core' const url = parseURL('/img.jpg?w=800&format=webp&quality=85') const entries = extractEntries(url.searchParams) const [config] = resolveConfigs(entries, builtinOutputFormats) const { transforms, parametersUsed } = generateTransforms( config, builtins, url.searchParams, { info: console.log, warn: console.warn, error: console.error } ) console.log(parametersUsed) // Set { 'w', 'format', 'quality' } ``` -------------------------------- ### vite-imagetools - Register the Vite plugin Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt The main entry point for Vite projects. Call inside `vite.config.ts`'s `plugins` array. Accepts an optional `VitePluginOptions` object to customize include/exclude patterns, default directives, transform extension, output format extension, caching, and metadata behavior. ```APIDOC ## imagetools(options?) ### Description Registers the Vite plugin for Imagetools. This function is the main entry point for Vite projects and should be called within the `plugins` array of your `vite.config.ts` file. It accepts an optional `VitePluginOptions` object to configure various aspects of the image processing pipeline, including file inclusion/exclusion patterns, default transformation directives, output format settings, caching behavior, and metadata handling. ### Parameters #### Options Object (`VitePluginOptions`) - **include** (RegExp | string | string[]) - Optional - Specifies patterns for files to include. Defaults to processing images with query parameters. - **exclude** (RegExp | string | string[]) - Optional - Specifies patterns for files to exclude. Defaults to excluding the `public` folder. - **removeMetadata** (boolean) - Optional - If true, strips EXIF/private metadata from output images. Defaults to false. - **defaultDirectives** (function) - Optional - A function that accepts a URL object and returns a `URLSearchParams` object with default directives to apply to every image import. - **cache** (object) - Optional - Configuration for disk caching. - **enabled** (boolean) - Whether to enable disk caching. Defaults to false. - **dir** (string) - The directory to use for caching transformed images. - **retention** (number) - The duration in seconds after which stale cache entries are removed. ### Request Example ```ts // vite.config.ts import { defineConfig } from 'vite' import { imagetools } from 'vite-imagetools' export default defineConfig({ plugins: [ imagetools({ include: /^[^?]+\.(avif|gif|heif|jpeg|jpg|png|tiff|webp)(\?.*)?$/, exclude: 'public/**/*', removeMetadata: true, defaultDirectives: (url) => { if (url.searchParams.has('hero')) { return new URLSearchParams({ format: 'webp', quality: '80' }) } return new URLSearchParams() }, cache: { enabled: true, dir: './node_modules/.cache/imagetools', retention: 172800 // remove stale entries after 48 hours (seconds) } }) ] }) ``` ``` -------------------------------- ### ProgressiveOptions Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/ProgressiveOptions.md This interface defines the options available for configuring progressive image loading. It includes a single property, `progressive`, which can be an empty string or the string 'true'. ```APIDOC ## Interface: ProgressiveOptions ### Description Defines options for progressive image loading. ### Properties #### progressive - **progressive** (string) - Optional - Can be `""` or `"true"` to enable progressive loading. ``` -------------------------------- ### Import and Transform an Image Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/getting-started.md Import an image with query parameters to specify transformations like width, height, and format. ```javascript import Image from 'example.jpg?w=400&h=300&format=webp' ``` -------------------------------- ### applyTransforms(transforms, image, removeMetadata?) Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Executes a list of ImageTransformation functions sequentially on a sharp image instance, returning the processed image and its metadata. ```APIDOC ## applyTransforms(transforms, image, removeMetadata?) ### Description Runs each `ImageTransformation` function in sequence on a sharp instance and returns `{ image, metadata }`. Optionally strips private EXIF data. ### Parameters #### Path Parameters - **transforms** (Array) - Required - An array of ImageTransformation functions to apply. - **image** (sharp.Sharp) - Required - The sharp image instance to transform. - **removeMetadata** (boolean) - Optional - If true, strips private EXIF data from the image. ### Request Example ```ts import sharp from 'sharp' import { applyTransforms, generateTransforms, resolveConfigs, extractEntries, parseURL, builtins, builtinOutputFormats } from 'imagetools-core' const url = parseURL('/photo.jpg?w=600&format=webp&quality=75') const entries = extractEntries(url.searchParams) const [config] = resolveConfigs(entries, builtinOutputFormats) const { transforms } = generateTransforms(config, builtins, url.searchParams) const image = sharp('/path/to/photo.jpg') const { image: outputImage, metadata } = await applyTransforms( transforms, image, true // strip EXIF metadata ) console.log(metadata.format) // 'webp' console.log(metadata.width) // 600 await outputImage.toFile('/path/to/output.webp') ``` ``` -------------------------------- ### resolveConfigs(entries, outputFormats) Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Computes the Cartesian product of directive entries to generate all possible image configurations, returning an array of ImageConfig objects. ```APIDOC ## resolveConfigs(entries, outputFormats) ### Description Takes extracted directive entries and computes every combination of values (cartesian product), returning an array of `ImageConfig` objects — one per image to be generated. ### Parameters #### Path Parameters - **entries** (Array<[string, string[]]>) - Required - An array of [key, values[]] tuples representing directive entries. - **outputFormats** (Array) - Required - An array of desired output formats. ### Request Example ```ts import { extractEntries, resolveConfigs, builtinOutputFormats } from 'imagetools-core' const entries: Array<[string, string[]]> = [ ['w', ['300', '600', '1200']], ['format', ['webp', 'avif']] ] const configs = resolveConfigs(entries, builtinOutputFormats) // 6 configs: { w: '300', format: 'webp' }, { w: '300', format: 'avif' }, // { w: '600', format: 'webp' }, { w: '600', format: 'avif' }, // { w: '1200', format: 'webp' }, { w: '1200', format: 'avif' } console.log(configs.length) // 6 ``` ``` -------------------------------- ### imagetools() Function Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/functions/imagetools.md The main function to initialize the ImageTools Vite plugin. It accepts optional user configurations. ```APIDOC ## imagetools() ### Description Initializes the ImageTools Vite plugin with optional user configurations. ### Signature `imagetools(userOptions?): Plugin$1` ### Parameters #### userOptions - **userOptions** (`Partial`) - Optional - Default: `{}` Allows customization of the plugin's behavior. ### Returns - `Plugin$1` The initialized Vite plugin instance. ``` -------------------------------- ### Parse URL and Resolve Image Configurations Source: https://github.com/jonaskruckenberg/imagetools/blob/main/packages/core/README.md Parse image transformation parameters from a URL and resolve them into configuration objects. This is useful for dynamic image processing based on URL queries. ```javascript import { parseURL, resolveConfigs } from 'imagetools-core' const src = new URL('file:///example.jpg?w=300;500;700&format=webp') // parses the url query parameters into an array of entries const parameters = parseURL(src) // this function handles the ArgumentList logic // and produces an array of config objects that can be passed to generateTransforms const configs = resolveConfigs(parameters) ``` -------------------------------- ### HSBOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/HSBOptions.md This interface specifies the properties for controlling Hue, Saturation, and Brightness adjustments. Each property accepts a string value. ```APIDOC ## Interface: HSBOptions ### Description Defines the options for HSB (Hue, Saturation, Brightness) transformations. ### Properties - **hue** (string) - Optional - Controls the hue adjustment. - **saturation** (string) - Optional - Controls the saturation adjustment. - **brightness** (string) - Optional - Controls the brightness adjustment. ``` -------------------------------- ### Configure Vite with vite-imagetools Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/getting-started.md Set up the vite-imagetools plugin in your vite.config.ts file to enable image processing. ```typescript import { defineConfig } from 'vite' import { imagetools } from 'vite-imagetools' export default defineConfig({ plugins: [imagetools()] }) ``` -------------------------------- ### FitOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/FitOptions.md The FitOptions interface specifies the available fitting strategies for image resizing. These options determine how the image content is scaled and positioned within the target dimensions. ```APIDOC ## Interface: FitOptions Defined in: [packages/core/src/transforms/fit.ts:8](https://github.com/JonasKruckenberg/imagetools/blob/aa84664d044e4b733cdf7005c6730584bc92ec90/packages/core/src/transforms/fit.ts#L8) ### Properties #### fit > **fit**: "cover" | "contain" | "fill" | "inside" | "outside" Defined in: [packages/core/src/transforms/fit.ts:9](https://github.com/JonasKruckenberg/imagetools/blob/aa84664d044e4b733cdf7005c6730584bc92ec90/packages/core/src/transforms/fit.ts#L9) Specifies the fitting strategy for the image. Possible values include: - `cover`: Scales the image to cover the entire target area, cropping if necessary. - `contain`: Scales the image to fit within the target area, preserving aspect ratio and adding letterboxing if necessary. - `fill`: Stretches the image to fill the target area, ignoring aspect ratio. - `inside`: Scales the image down to fit within the target area if it's larger, preserving aspect ratio. If the image is smaller, it remains unchanged. - `outside`: Scales the image up to fill the target area if it's smaller, preserving aspect ratio. If the image is larger, it remains unchanged. ``` -------------------------------- ### Default Include Path Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/types/interfaces/VitePluginOptions.md Specifies which image file paths to include for processing. Defaults to common image formats with query parameters. ```typescript '**/*.{heif,avif,jpeg,jpg,png,tiff,webp,gif}?*' ``` -------------------------------- ### Compute Image Configurations with resolveConfigs Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Generates all possible image configurations by computing the cartesian product of directive entries. Returns an array of ImageConfig objects. ```typescript import { extractEntries, resolveConfigs, builtinOutputFormats } from 'imagetools-core' const entries: Array<[string, string[]]> = [ ['w', ['300', '600', '1200']], ['format', ['webp', 'avif']] ] const configs = resolveConfigs(entries, builtinOutputFormats) // 6 configs: { w: '300', format: 'webp' }, { w: '300', format: 'avif' }, // { w: '600', format: 'webp' }, { w: '600', format: 'avif' }, // { w: '1200', format: 'webp' }, { w: '1200', format: 'avif' } console.log(configs.length) // 6 ``` -------------------------------- ### Configure Default Directives with a Function Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/types/interfaces/VitePluginOptions.md Use a function to dynamically set default directives based on the asset URL. This allows for conditional presets. ```javascript import { defineConfig } from 'vite' import { imagetools } from 'vite-imagetools' export default defineConfig({ plugins: [ imagetools({ defaultDirectives: (url) => { if (url.searchParams.has('spotify')) { return new URLSearchParams({ tint: 'ffaa22' }) } return new URLSearchParams() } }) ] }) ``` -------------------------------- ### imagetools Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/README.md The main entry point or factory function for the imagetools library, likely used to initialize or configure image processing capabilities. ```APIDOC ## imagetools ### Description Main entry point for the imagetools library. ### Signature imagetools(options?: VitePluginOptions): Plugin ``` -------------------------------- ### Apply Lossless Compression Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/directives.md Enable lossless compression for supported formats like AVIF, HEIF, JXL, and WebP using the 'lossless' directive. It can be set with or without an explicit 'true' value. ```javascript import losslessWebp from 'example.jpg?format=webp&lossless' ``` ```javascript import losslessAvif from 'example.jpg?format=avif&lossless=true' ``` -------------------------------- ### ResizeOptions Properties Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/ResizeOptions.md This interface defines the properties available for configuring image resizing operations. ```APIDOC ## Interface: ResizeOptions ### Properties #### w - **w** (string) - Optional - width in pixels #### h - **h** (string) - Optional - height in pixels #### aspect - **aspect** (string) - Optional - aspect ratio #### allowUpscale - **allowUpscale** (string) - Optional - Whether to allow making images larger. This is generally a waste, so is disabled by default. #### basePixels - **basePixels** (string) - Optional - The width in pixels for the 1x pixel density descriptor. If supplied, output will use pixel density descriptors rather than width descriptors. ``` -------------------------------- ### entries Source: https://github.com/jonaskruckenberg/imagetools/blob/main/packages/vite/README.md Builds all possible combinations of given entries and returns them as an array of objects suitable for transforms. ```APIDOC ## Function: entries ### Description This function builds up all possible combinations of the given entries and returns it as an array of objects that can be given to a the transforms. ### Signature ▸ (`entries`, `outputFormats`): `Record[]` ### Parameters #### Parameters - **entries** (`[string, string[]][]`) - Required - The url parameter entries - **outputFormats** (`Record`) - Required - Description not provided in source ### Returns `Record[]` - An array of directive options ``` -------------------------------- ### FlipOptions Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/FlipOptions.md The FlipOptions interface specifies the properties that can be used to control image flipping. The 'flip' property accepts an empty string or 'true' to enable flipping. ```APIDOC ## Interface: FlipOptions ### Description Defines the options for image flipping transformations. ### Properties #### flip - **flip** (string) - Optional - Accepts `""` or `"true"` to enable horizontal or vertical flipping respectively. ``` -------------------------------- ### HSBOptions Interface Properties Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/interfaces/HSBOptions.md This interface outlines the configurable options for HSB transformations, including brightness, hue, and saturation adjustments. ```APIDOC ## Interface: HSBOptions ### Description Defines options for HSB color transformations. ### Properties #### hue - **hue** (string) - Required - The hue value to apply. #### saturation - **saturation** (string) - Required - The saturation value to apply. #### brightness - **brightness** (string) - Required - The brightness value to apply. ``` -------------------------------- ### BackgroundOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/interfaces/BackgroundOptions.md The BackgroundOptions interface includes properties for configuring background transformations. ```APIDOC ## Interface: BackgroundOptions ### Description Defines configuration options for background transformations. ### Properties #### background - **background** (string) - Required - Specifies the background value. ``` -------------------------------- ### LosslessOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/LosslessOptions.md Defines the options available for lossless image processing. The `lossless` property can be an empty string or the string 'true' to enable lossless compression. ```APIDOC ## Interface: LosslessOptions ### Description This interface specifies options for lossless image transformations. It is defined within the core imagetools package. ### Properties #### lossless - **Type**: `""` | `"true"` - **Description**: Specifies whether to use lossless compression. Accepts an empty string or the literal string 'true' to enable. ### Defined In `packages/core/src/transforms/lossless.ts:4` ``` -------------------------------- ### ProgressiveOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/interfaces/ProgressiveOptions.md The ProgressiveOptions interface defines configuration options for progressive image loading. It includes a 'progressive' property that accepts specific string values to enable or disable this feature. ```APIDOC ## Interface: ProgressiveOptions ### Description Defines configuration options for progressive image loading. ### Properties #### progressive - **progressive** (string) - Required - Specifies the progressive loading behavior. Accepted values are `""` (empty string, likely default/disabled) or `"true"` (enabled). ``` -------------------------------- ### Import Image Metadata Source: https://github.com/jonaskruckenberg/imagetools/blob/main/examples/vite-simple/README.md Import image metadata, including source URL, width, and height, after resizing the image. This is useful for obtaining image dimensions or other properties for use in your application. ```typescript import { src as placeholder, width, height } from '../example.jpg?w=300&as=metadata' ``` -------------------------------- ### hsb Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/variables/hsb.md The `hsb` transform factory allows for the adjustment of Hue, Saturation, and Brightness. It accepts an `HSBOptions` object to configure these adjustments. ```APIDOC ## Variable: hsb > `const` **hsb**: [`TransformFactory`](../type-aliases/TransformFactory.md)<[`HSBOptions`](../interfaces/HSBOptions.md)> Defined in: [packages/core/src/transforms/hsb.ts:10](https://github.com/JonasKruckenberg/imagetools/blob/aa84664d044e4b733cdf7005c6730584bc92ec90/packages/core/src/transforms/hsb.ts#L10) ``` -------------------------------- ### QualityOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/QualityOptions.md The QualityOptions interface is used to configure image quality settings. It has a single property, 'quality', which specifies the desired quality level as a string. ```APIDOC ## Interface: QualityOptions ### Description Defines options for image quality transformations. ### Properties #### quality - **quality** (string) - Specifies the desired image quality level. ``` -------------------------------- ### w / h — Resize by Width and/or Height Source: https://context7.com/jonaskruckenberg/imagetools/llms.txt Resizes the image to the specified pixel dimensions. Omitting one dimension scales it proportionally. Passing semicolon-separated values generates multiple output images from a single import. ```APIDOC ## w / h — Resize by Width and/or Height ### Description Resizes an image to the specified pixel dimensions using the `w` (width) and `h` (height) directives. If only one dimension is provided, the other is calculated proportionally to maintain the aspect ratio. Multiple semicolon-separated values for a dimension can be used to generate multiple output images from a single import statement, resulting in an array of URLs. ### Parameters - **w** (number) - Optional - The desired width in pixels. - **h** (number) - Optional - The desired height in pixels. - **withoutEnlargement** (boolean) - Optional - If true, prevents the image from being scaled up beyond its original dimensions. - **fit** (string) - Optional - Specifies the fitting strategy when both width and height are provided (e.g., `cover`, `contain`, `fill`, `inside`, `outside`). ### Usage Examples ```js // Single width — height auto-calculated import img300 from './photo.jpg?w=300' // Single height — width auto-calculated import img200h from './photo.jpg?h=200' // Multiple widths in one import → returns an array of URLs import [img300, img600, img1200] from './photo.jpg?w=300;600;1200' // Explicit width + height with fit strategy import cropped from './photo.jpg?w=400&h=300&fit=cover' // Prevent upscaling beyond the image's intrinsic size import safe from './photo.jpg?w=300;600;1200&withoutEnlargement' ``` ``` -------------------------------- ### Using Custom Image Presets in Page Components Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/extending.md Import images in your page components using the custom preset name defined in your `resolveConfigs` function. This allows you to apply specific image configurations based on the preset. ```typescript // page.tsx, etc import img_urls from "./myimage.png?mypreset" ``` -------------------------------- ### LosslessOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/interfaces/LosslessOptions.md The LosslessOptions interface defines the available options for controlling lossless image compression. ```APIDOC ## Interface: LosslessOptions ### Description Defines options for lossless image transformations. ### Properties #### lossless - **Type**: `""` | `"true"` - **Description**: Specifies whether to use lossless compression. An empty string or 'true' enables lossless compression. ``` -------------------------------- ### Convert Image Format Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/directives.md Use the 'format' directive to convert an image to a specified format. Multiple formats can be requested. ```javascript import Image from 'example.jpg?format=webp' ``` ```javascript import Images from 'example.jpg?format=webp;avif;jxl' ``` -------------------------------- ### TintOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/TintOptions.md The TintOptions interface specifies the properties available for tinting images. It currently includes a single property, 'tint', which is a string representing the color to apply. ```APIDOC ## Interface: TintOptions Defined in: [packages/core/src/transforms/tint.ts:4](https://github.com/JonasKruckenberg/imagetools/blob/aa84664d044e4b733cdf7005c6730584bc92ec90/packages/core/src/transforms/tint.ts#L4) ### Properties #### tint > **tint**: `string` Defined in: [packages/core/src/transforms/tint.ts:5](https://github.com/JonasKruckenberg/imagetools/blob/aa84664d044e4b733cdf7005c6730584bc92ec90/packages/core/src/transforms/tint.ts#L5) Represents the color to be applied as a tint. This should be a valid CSS color string. ``` -------------------------------- ### Set Image Fit Method - JavaScript Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/directives.md Specify how an image should fit within given dimensions using methods like `cover`, `contain`, `fill`, `inside`, or `outside`. ```javascript import Image from 'example.jpg?fit=cover' ``` -------------------------------- ### Importing Directives for Reuse Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/extending.md Import directives like 'resize' and 'format' from 'imagetools' to reuse them within your custom directives. This allows for modular and composable image processing logic. ```javascript import { resize, format } from 'imagetools' ``` -------------------------------- ### KernelOptions Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/KernelOptions.md Defines the available kernel types for image resizing and transformations. Users can specify one of the predefined kernel strings. ```APIDOC ## Interface: KernelOptions ### Description This interface specifies the options for kernel selection in image transformations. It allows users to choose from a predefined set of interpolation kernels. ### Properties #### kernel - **Type**: `"nearest"` | `"cubic"` | `"mitchell"` | `"lanczos2"` | `"lanczos3"` - **Description**: Specifies the interpolation kernel to use for image resizing. Available options include nearest-neighbor, cubic spline, Mitchell-Netravali, Lanczos2, and Lanczos3. ### Example Usage (Conceptual) ```typescript // Assuming a function that accepts KernelOptions const options: KernelOptions = { kernel: "lanczos3" }; // Example of how it might be used in an image processing function // resizeImage(image, { width: 100, height: 100, kernel: "lanczos3" }); ``` ``` -------------------------------- ### Basic URL Transformation Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/guide/getting-started.md Specify image transformations directly in the URL as query parameters. ```plaintext ?w=300 ``` -------------------------------- ### Img Interface Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/core/src/interfaces/Img.md The Img interface represents the output format for images, containing properties for source, width, height, and optional srcset. ```APIDOC ## Interface: Img ### Description The img output format. ### Properties - **src** (string) - The image source URL. - **w** (number) - The intrinsic width of the image. - **h** (number) - The intrinsic height of the image. May not be the rendered height. Helps prevent reflow. See https://html.com/attributes/img-height/ - **srcset?** (string) - Optional srcset attribute for responsive images. ``` -------------------------------- ### Fit Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/directives.md Specifies how an image should fit when both width and height are provided, using methods like cover, contain, fill, inside, or outside. ```APIDOC ## Fit ### Description When both a `width` and `height` are provided, this directive specifies the method by which the image should fit. ### Keyword `fit` ### Type `cover` | `contain` | `fill` | `inside` | `outside` ### Example ```js import Image from 'example.jpg?fit=cover' ``` ``` -------------------------------- ### Background Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/_media/directives.md Sets a background color for directives that fill empty spots, like rotation. Parsed by the color-string library. ```APIDOC ## Background ### Description Instructs various directives (e.g., [rotate](#rotate)) to use the specified color when filling empty spots in the image. The argument is parsed by the [color-string](https://www.npmjs.com/package/color-string) library. ### Keyword `background` ### Type `string` ### Note This directive does nothing on its own and must be used with another directive. Only one value can be set. ### Example ```js import Image from 'foo.jpg?background=#FFFFFFAA' import Image from 'foo.jpg?background=hsl(360, 100%, 50%)' import Image from 'foo.jpg?background=rgb(200, 200, 200)' import Image from 'foo.jpg?background=blue' ``` ``` -------------------------------- ### FitOptions Source: https://github.com/jonaskruckenberg/imagetools/blob/main/docs/vite/src/interfaces/FitOptions.md The FitOptions interface specifies the 'fit' property, which accepts one of the following string literals to determine the fitting behavior: 'cover', 'contain', 'fill', 'inside', or 'outside'. ```APIDOC ## Interface: FitOptions ### Description Defines the options for fitting an image within specified dimensions. ### Properties #### fit - **fit** (string) - Required - One of the following values: "cover" | "contain" | "fill" | "inside" | "outside" - `cover`: Resizes the image to cover the entire area, cropping if necessary. - `contain`: Resizes the image to fit within the area, preserving aspect ratio and adding letterboxing if necessary. - `fill`: Resizes the image to fill the area, potentially distorting the aspect ratio. - `inside`: Resizes the image to be as large as possible while ensuring its dimensions are less than or equal to the target dimensions. - `outside`: Resizes the image to be as small as possible while ensuring its dimensions are greater than or equal to the target dimensions. ### Defined in packages/core/dist/transforms/fit.d.ts:4 ```