ImageHandler.js
Overview
The ImageHandler class is responsible for managing image processing and caching in a server site render system. It supports detecting image formats, handling external image downloads, caching images, and creating optimized versions of images in various sizes and formats (e.g., .webp).
Content
Methods
detectImage
- Purpose: Determines if a file path corresponds to an image file.
- Parameters:
path(string): The file path to check.
- Returns:
trueif the file is an image; otherwise,false. - Supported Formats:
.jpeg,.jpg,.tif,.tiff,.png,.webp,.bmp.
detectWebpImage
- Purpose: Checks if a file path corresponds to a
.webpimage. - Parameters:
path(string): The file path to check.
- Returns:
trueif the file is a.webpimage; otherwise,false.
detectExternalImage
- Purpose: Determines if a URL points to an external image by extracting the
sourcequery parameter. - Parameters:
url(string): The URL path.urlParams(string): Query parameters to append to the URL.
- Returns: The value of the
sourcequery parameter if present; otherwise,null.
getFromCache
- Purpose: Retrieves an image from the cache if it exists, or generates it if not.
- Parameters:
website(string): The website identifier.url(string): The image URL path.urlParams(string): Query parameters for the URL.
- Returns:
- An object containing:
type('asset'or'error').path(string): The path to the cached image or an error message.
- An object containing:
generateImages
- Purpose: Handles the generation and caching of images, including external image downloads and
.webpconversion. - Parameters:
website(string): The website identifier.url(string): The image URL path.urlParams(string): Query parameters for the URL.buildFolder(string, optional): The folder path where the site is being built.
- Returns: A promise resolving to an object containing:
type('asset'or'error').path(string): The path to the cached image or an error message.
- Key Features:
- Checks for existing cached or
.webpfiles. - Creates missing directories if necessary.
- Resizes images and generates
.webpversions.
- Checks for existing cached or
prepareSources
- Purpose: Creates resized versions of an image (600px and 1200px width) and converts them to
.webp. - Parameters:
path(string): The file path of the original image.
- Returns:
trueafter the resized versions are created. - Behavior:
- Resizes images exceeding 600px and 1200px widths.
- Saves resized images with suffixes
-600and-1200.
downloadExternalImage
- Purpose: Downloads an external image, caches it, and generates optimized versions.
- Parameters:
website(string): The website identifier.url(string): The image URL path.urlParams(string): Query parameters for the URL.
- Returns: The local path to the cached image.
- Behavior:
- Constructs the full external URL using the
sourcequery parameter. - Downloads the image and saves it to the cache.
- Creates
.webpand resized versions of the image.
- Constructs the full external URL using the