Utility functions for image analysis, metadata extraction, color analysis, and dimension calculations.
Functions for extracting image dimensions and metadata from files.
/**
* Asynchronously gets image dimensions and metadata
* @param file - Gatsby file node
* @returns Promise resolving to dimensions object
*/
function getImageSizeAsync(file: FileNode): Promise<ImageDimensions>;
/**
* Synchronously gets image dimensions (deprecated, slow)
* @param file - Gatsby file node
* @returns Dimensions object
* @deprecated This function is slow and will be removed in next major version
*/
function getImageSize(file: FileNode): ImageDimensions;
interface ImageDimensions {
width: number; // Image width in pixels
height: number; // Image height in pixels
type: string; // Image format/type (jpeg, png, webp, etc.)
}
/**
* Retrieves comprehensive image metadata including dominant color
* @param file - Gatsby file node
* @param getDominantColor - Whether to extract dominant color (expensive operation)
* @param cache - Optional Gatsby cache instance for performance
* @returns Promise resolving to metadata object
*/
function getImageMetadata(
file: FileNode,
getDominantColor?: boolean,
cache?: GatsbyCache
): Promise<IImageMetadata>;
interface IImageMetadata {
width?: number; // Image width in pixels
height?: number; // Image height in pixels
format?: string; // Image format (jpeg, png, webp, etc.)
density?: number; // Image density/DPI
dominantColor?: string; // Dominant color as hex string (if requested)
}Usage Examples:
const sharp = require("gatsby-plugin-sharp");
// Get image dimensions asynchronously (recommended)
const dimensions = await sharp.getImageSizeAsync(fileNode);
console.log(`Image is ${dimensions.width}x${dimensions.height} ${dimensions.type}`);
// Get dimensions synchronously (deprecated)
const syncDimensions = sharp.getImageSize(fileNode);
console.log(`Sync: ${syncDimensions.width}x${syncDimensions.height}`);
// Get comprehensive metadata with dominant color
const metadata = await sharp.getImageMetadata(fileNode, true, cache);
console.log(`Image: ${metadata.width}x${metadata.height} ${metadata.format}`);
console.log(`Dominant color: ${metadata.dominantColor}`);
// Get metadata without dominant color for better performance
const fastMetadata = await sharp.getImageMetadata(fileNode, false);
console.log(`Quick metadata: ${fastMetadata.format}`);Functions for extracting color information from images.
/**
* Extracts dominant color from image
* @param absolutePath - Absolute path to image file
* @returns Promise resolving to hex color string
*/
function getDominantColor(absolutePath: string): Promise<string>;Usage Examples:
const sharp = require("gatsby-plugin-sharp");
// Extract dominant color
const dominantColor = await sharp.getDominantColor(fileNode.absolutePath);
console.log(`Dominant color: ${dominantColor}`); // e.g., "#3a5998"
// Use dominant color as background
const resultWithBg = await sharp.queueImageResizing({
file: fileNode,
args: {
width: 400,
background: dominantColor
},
reporter
});Functions for getting detailed image statistics and properties.
/**
* Retrieves image statistics and properties
* @param options - Configuration object
* @param options.file - Gatsby file node
* @param options.reporter - Gatsby reporter instance
* @returns Promise resolving to image statistics
*/
function stats(options: {
file: FileNode;
reporter: Reporter;
}): Promise<ImageStats>;
interface ImageStats {
isTransparent: boolean; // Whether image has transparency
}Usage Examples:
const sharp = require("gatsby-plugin-sharp");
// Get image statistics
const imageStats = await sharp.stats({ file: fileNode, reporter });
if (imageStats.isTransparent) {
console.log("Image has transparency");
// Handle transparent images differently
}/**
* Converts RGB values to hex color string
* @param red - Red component (0-255)
* @param green - Green component (0-255)
* @param blue - Blue component (0-255)
* @returns Hex color string (e.g., "#ff0000")
*/
function rgbToHex(red: number, green: number, blue: number): string;Usage Examples:
const { rgbToHex } = require("gatsby-plugin-sharp/src/utils");
const hexColor = rgbToHex(255, 0, 0); // "#ff0000"
const blueHex = rgbToHex(0, 100, 200); // "#0064c8"Functions for calculating responsive image sizes and breakpoints.
/**
* Calculates appropriate image sizes for responsive layouts
* @param args - Configuration arguments
* @returns Object with sizes array and dimension metadata
*/
function calculateImageSizes(args: ImageSizeArgs): ImageSizeResult;
/**
* Calculates sizes for fixed layout images
* @param args - Fixed image arguments
* @returns Sizes calculation object
*/
function fixedImageSizes(args: FixedImageSizeArgs): ImageSizeResult;
/**
* Calculates sizes for responsive layout images
* @param args - Responsive image arguments
* @returns Sizes calculation object
*/
function responsiveImageSizes(args: ResponsiveImageSizeArgs): ImageSizeResult;
interface ImageSizeResult {
sizes: number[]; // Array of widths to generate
aspectRatio: number; // Image aspect ratio
presentationWidth: number; // Display width
presentationHeight: number; // Display height
unscaledWidth: number; // Original calculated width
}/**
* Calculates final dimensions based on fit options
* @param dimensions - Original image dimensions
* @param options - Resize options including fit, width, height
* @returns Object with calculated width, height, aspectRatio
*/
function getDimensionsAndAspectRatio(
dimensions: { width: number; height: number },
options: {
width?: number;
height?: number;
fit?: "cover" | "contain" | "fill" | "inside" | "outside";
}
): {
width: number;
height: number;
aspectRatio: number;
};Usage Examples:
const { getDimensionsAndAspectRatio } = require("gatsby-plugin-sharp/src/utils");
// Calculate dimensions for cover fit
const result = getDimensionsAndAspectRatio(
{ width: 1200, height: 800 },
{ width: 400, height: 400, fit: "cover" }
);
console.log(result); // { width: 400, height: 400, aspectRatio: 1 }
// Calculate dimensions for contain fit
const containResult = getDimensionsAndAspectRatio(
{ width: 1200, height: 800 },
{ width: 400, height: 400, fit: "contain" }
);
console.log(containResult); // { width: 400, height: 267, aspectRatio: 1.5 }/**
* Generates CSS sizes attribute for responsive images
* @param width - Image width
* @param layout - Image layout type
* @returns Sizes string for use in img tag
*/
function getSizes(width: number, layout: string): string | undefined;Usage Examples:
const { getSizes } = require("gatsby-plugin-sharp/src/utils");
const constrainedSizes = getSizes(800, "constrained");
console.log(constrainedSizes); // "(min-width: 800px) 800px, 100vw"
const fixedSizes = getSizes(400, "fixed");
console.log(fixedSizes); // "400px"
const fullWidthSizes = getSizes(1200, "fullWidth");
console.log(fullWidthSizes); // "100vw"/**
* Generates srcSet string from array of images
* @param images - Array of image objects with src and width
* @returns Formatted srcSet string
*/
function getSrcSet(images: Array<{ src: string; width: number }>): string;Usage Examples:
const { getSrcSet } = require("gatsby-plugin-sharp/src/utils");
const images = [
{ src: "/image-400.webp", width: 400 },
{ src: "/image-800.webp", width: 800 },
{ src: "/image-1200.webp", width: 1200 }
];
const srcSet = getSrcSet(images);
console.log(srcSet);
// "/image-400.webp 400w,\n/image-800.webp 800w,\n/image-1200.webp 1200w"Image dimensions and metadata are automatically cached to improve performance:
// Internal caching system
const imageSizeCache = new Map(); // Caches dimensions by content digest
const dominantColorCache = new Map(); // Caches dominant colors by absolute path
const metadataCache = new Map(); // Caches comprehensive metadataThe plugin automatically manages caches based on:
getImageSizeAsync over deprecated getImageSizeAll utility functions include error handling for common issues:
Usage Examples:
try {
const dimensions = await sharp.getImageSizeAsync(fileNode);
console.log(`Success: ${dimensions.width}x${dimensions.height}`);
} catch (error) {
console.error(`Failed to get image dimensions: ${error.message}`);
}
try {
const dominantColor = await sharp.getDominantColor(fileNode.absolutePath);
console.log(`Dominant color: ${dominantColor}`);
} catch (error) {
console.error(`Failed to extract dominant color: ${error.message}`);
// Fallback to default color
const fallbackColor = "#cccccc";
}