imagetools

repository·main·Indexed 22 days ago

https://github.com/jonaskruckenberg/imagetools

A suite of tools for compile-time image transformation and optimization powered by the sharp library. It provides imagetools-core for the transformation engine and vite-imagetools for Vite integration, allowing developers to resize images, convert formats, and generate srcsets using import directives and query parameters.

Tokens
44.6K
Snippets
224
Records
264
Agent score
78%

What's inside imagetools

  1. Overview of Imagetools

    main

    Imagetools is a toolbox of import directives designed to transform and optimize images at compile-time. It leverages sharp to perform high-performance image processing.

    Key capabilities include:

    • Outputting modern image formats.
    • Resizing images.
    • Generating srcset attributes easily.
    • Fast performance during development.
    • Removing image metadata for privacy and optimization.
    • Extensible architecture for custom transformations.
  2. Explore the vite/src API surface

    main

    The vite/src directory contains the core logic and type definitions for the imagetools integration within Vite. It provides a comprehensive set of interfaces, type aliases, variables, and functions used to manipulate images via URL parameters or configuration.

    Key areas of the API include:

    • Interfaces: Definitions for transformation options such as ResizeOptions, BlurOptions, FormatOptions, and RotateOptions.
    • Type Aliases: Core types like ImageTransformation, OutputFormat, and ImageConfig.
    • Functions: Core logic including applyTransforms, generateTransforms, getMetadata, and parseURL.
    • Variables: Predefined transformation values and helper functions like resize, blur, grayscale, and format.
  3. Understand the ImageMetadata interface

    main

    The ImageMetadata interface is a core type in imagetools that provides comprehensive information about an image. It extends the base Metadata interface (which contains standard image properties like format, width, height, and channels) by adding specialized properties related to image processing transformations and specific tool configurations.

    Key additions in ImageMetadata include:

    • Transformation State: Tracks if the image has been flip, flop, rotate, grayscale, invert, or flattened.
    • Processing Parameters: Includes properties like blur, brightness, contrast, hue, saturation, tint, quality, and kernel (e.g., "nearest", "cubic", "lanczos3").
    • Layout & Positioning: Properties like aspect, fit, position (e.g., "center", "entropy", "attention"), and pixelDensityDescriptor.
    • Advanced Metadata: Includes allowUpscale, backgroundDirective, and lossless flags.
  4. How imagetools optimizes images

    main

    Instead of manually resizing and exporting images in tools like Photoshop, imagetools allows you to perform image transformations directly within your code via import queries. By appending transformation parameters to an image import path, the tool automatically handles the resizing and optimization during the build process. This ensures that images are served at the correct dimensions and file sizes, improving SEO and reducing data costs for users.

    import Image from 'example.jpeg?w=300&h=400'
  5. Generate multiple image versions with argument lists

    main

    You can generate multiple variations of an image from a single import statement by providing a semicolon-separated list of values for a directive.

    If you combine multiple directives with multiple arguments, imagetools will generate a combination for every possible pair. For example, ?w=300;500&format=webp;avif will generate 4 images (300w/webp, 300w/avif, 500w/webp, 500w/avif).

    // Generates three images with widths of 300, 500, and 700 pixels
    import Image300 from 'example.jpg?w=300;500;700'
    
    // Generates 9 different images (3 widths x 3 formats)
    import Images from 'example.jpg?w=300;500;700&format=webp;avif;jpg'
  6. Create a Custom Directive

    main

    A Directive (also known as a TransformFactory) is a function that takes a configuration object and a context object, and returns either an ImageTransformation function or undefined.

    Directives are responsible for parsing incoming arguments (which are strings) and determining if a transformation should be applied. If the transformation is applicable, you must return a function that accepts a sharp instance and returns the transformed image.

    To reuse existing directives, import them from imagetools and invoke them within your factory, ensuring you pass the ctx (context) object so that warnings and keyword usage tracking work correctly.

    type TransformFactory<A = {}> = (
      metadata: Partial<ImageConfig & A>,
      ctx: TransformFactoryContext
    ) => ImageTransformation | undefined
  7. Understand the OutputFormat type alias

    main

    The OutputFormat type defines the structure of the function returned by an image import in imagetools. It is a higher-order function that follows a two-step execution pattern:

    1. Initialization: You call the function with an optional array of strings (args?).
    2. Execution: The resulting function is then called with an array of ProcessedImageMetadata objects, which finally returns the actual image data (of type unknown).

    This pattern allows the image import to be configured with specific arguments before the metadata from the processing pipeline is injected to produce the final output.

    // Conceptual representation of the OutputFormat signature
    type OutputFormat = (args?: string[]) => (metadata: ProcessedImageMetadata[]) => unknown;
  8. How imagetools optimizes images via import syntax

    main

    Instead of manually resizing and exporting images in external editors, imagetools allows you to perform image transformations directly within your code using URL query parameters in the import statement. This automates the process of resizing and optimizing images during the build step, ensuring you serve the correct dimensions and reducing page weight.

    import Image from 'example.jpeg?w=300&h=400'
  9. Use Output Directives for metadata, picture, srcset, and url

    main

    Imagetools supports specific output directives that change how the processed image information is returned. Instead of just a URL, you can request different data structures:

    • metadata: Returns the image metadata.
    • picture: Returns a <picture> element structure.
    • srcset: Returns a srcset string.
    • url: Returns the image URL.