- Core Classes
- Classification System
- Enhancement Features
- Utility Classes
- Types and Interfaces
- Error Handling
The main class for image alignment, comparison, and diff generation.
import { ImageProcessor } from "auto-image-diff";
const processor = new ImageProcessor();Aligns two images using various alignment strategies.
Parameters:
referenceImage: string- Path to the reference (baseline) imagetargetImage: string- Path to the target image to alignoutputPath: string- Path where the aligned image will be savedoptions?: AlignmentOptions- Optional alignment configuration
Returns: Promise<AlignmentResult>
Example:
const result = await processor.alignImages(
'baseline.png',
'screenshot.png',
'aligned.png',
{
method: 'opencv',
opencvDetector: 'orb',
threshold: 0.8
}
);
console.log(`Aligned with offset: ${result.offset.x}, ${result.offset.y}`);Compares two images and calculates difference metrics.
Parameters:
image1Path: string- Path to first imageimage2Path: string- Path to second imagethreshold?: number- Percentage threshold for equality (default: 0.1)
Returns: Promise<ComparisonResult>
Example:
const result = await processor.compareImages('before.png', 'after.png', 0.5);
if (result.isEqual) {
console.log('Images are visually identical');
} else {
console.log(`${result.statistics.pixelsDifferent} pixels differ`);
}Generates a visual difference image with optional enhancements.
Parameters:
image1Path: string- Path to reference imageimage2Path: string- Path to comparison imageoutputPath: string- Path for output diff imageoptions?: DiffOptions- Diff generation options
Returns: Promise<ComparisonResult>
Example:
const result = await processor.generateDiff(
'original.png',
'modified.png',
'diff.png',
{
highlightColor: 'magenta',
lowlight: true,
runClassification: true,
generateCssSuggestions: true,
embedMetadata: true,
exclusions: {
regions: [
{ x: 0, y: 0, width: 200, height: 50 } // Exclude header
]
}
}
);
console.log('Classification:', result.classification);
console.log('CSS Fixes:', result.cssSuggestions);Handles batch processing of multiple images with parallel execution support.
import { BatchProcessor } from "auto-image-diff";
const batchProcessor = new BatchProcessor();Processes all images in two directories.
Parameters:
referenceDir: string- Directory with reference imagestargetDir: string- Directory with target imagesoptions: BatchOptions- Batch processing configuration
Returns: Promise<BatchResult>
Example:
const result = await batchProcessor.processBatch(
'./screenshots/baseline',
'./screenshots/current',
{
outputDir: './results',
pattern: '**/*.png',
recursive: true,
parallel: true,
maxConcurrency: 8,
smartPairing: true,
runClassification: true
}
);
console.log(`Processed ${result.processed}/${result.totalFiles} images`);
console.log(`Average difference: ${result.summary.averageDifference}%`);Generates HTML summary report for batch results.
Parameters:
results: BatchResult- Batch processing resultsoutputDir: string- Directory for report files
Returns: Promise<void>
Manages the classification pipeline for analyzing differences.
import { ClassifierManager } from "auto-image-diff/lib/classifiers";
const manager = new ClassifierManager();Classifies multiple difference regions.
Parameters:
regions: DifferenceRegion[]- Regions to classifycontext: AnalysisContext- Image analysis context
Returns: RegionClassification[]
Registers a custom classifier.
Parameters:
classifier: DifferenceClassifier- Classifier instance
Abstract base class for creating custom classifiers.
abstract class DifferenceClassifier {
abstract classify(
region: DifferenceRegion,
context: AnalysisContext
): ClassificationResult | null;
abstract canClassify(
region: DifferenceRegion,
context: AnalysisContext
): boolean;
}Example Custom Classifier:
class AnimationClassifier extends DifferenceClassifier {
constructor() {
super('animation', 10); // name and priority
}
canClassify(region, context) {
// Check if region might be an animation
return region.bounds.width > 50 && region.bounds.height > 50;
}
classify(region, context) {
// Analyze for animation patterns
const isAnimation = this.detectAnimationPattern(region, context);
if (isAnimation) {
return {
type: DifferenceType.CONTENT,
subType: 'animation',
confidence: 0.9,
details: { frameCount: 24 }
};
}
return null;
}
}Generates CSS suggestions to fix style differences.
import { CssFixSuggester } from "auto-image-diff";
const suggester = new CssFixSuggester();Analyzes differences and suggests CSS fixes.
Parameters:
imagePath1: string- Original image pathimagePath2: string- Modified image pathclassification: ClassificationSummary- Classification results
Returns: Promise<FixSuggestion[]>
Example:
const suggestions = await suggester.suggestFixes(
'original.png',
'styled.png',
classificationResult
);
suggestions.forEach(fix => {
console.log(`Selector: ${fix.selector}`);
console.log(`CSS: ${fix.css.map(c => `${c.property}: ${c.value}`).join('; ')}`);
});Captures execution context and Git information.
import { MetadataEnhancer } from "auto-image-diff";
const enhancer = new MetadataEnhancer();Collects comprehensive metadata about the execution environment.
Returns: Promise<EnhancedMetadata>
Example:
const metadata = await enhancer.collectMetadata();
console.log('Git commit:', metadata.gitInfo?.currentCommit);
console.log('Node version:', metadata.executionEnvironment.nodeVersion);
console.log('Platform:', metadata.systemInfo.platform);Interactive refinement tool for improving exclusion regions.
import { ProgressiveRefiner } from "auto-image-diff";
const refiner = new ProgressiveRefiner();Starts an interactive refinement session.
Parameters:
baseImage: string- Baseline image pathtargetImage: string- Target image pathoptions: RefinementOptions- Refinement configuration
Returns: Promise<RefinementSession>
Intelligent file pairing for batch processing.
const pairing = new SmartPairing();
const pairs = pairing.findBestMatches(referenceFiles, targetFiles);Creates exclusion masks from configuration.
const generator = new MaskGenerator();
const maskPath = await generator.generateMask(width, height, exclusions);Embeds metadata directly into PNG files.
const embedder = new PngMetadataEmbedder();
await embedder.embedMetadata(imagePath, metadata);
const extracted = await embedder.extractMetadata(imagePath);interface AlignmentOptions {
method: "feature" | "phase" | "subimage" | "opencv";
threshold?: number;
opencvDetector?: "orb" | "akaze" | "brisk";
}interface ComparisonResult {
difference: number;
diffImagePath?: string;
isEqual: boolean;
statistics: {
pixelsDifferent: number;
totalPixels: number;
percentageDifferent: number;
};
classification?: ClassificationSummary;
cssSuggestions?: FixSuggestion[];
}interface BatchOptions {
pattern?: string;
recursive?: boolean;
outputDir: string;
threshold?: number;
parallel?: boolean;
maxConcurrency?: number;
exclusions?: ExclusionsConfig;
runClassification?: boolean;
smartPairing?: boolean;
}interface DifferenceRegion {
bounds: {
x: number;
y: number;
width: number;
height: number;
};
pixelCount: number;
differencePixels: number;
differencePercentage: number;
}interface ClassificationResult {
type: DifferenceType;
confidence: number; // 0-1
subType?: string;
details?: Record<string, unknown>;
}interface ExclusionsConfig {
regions?: Array<{
x: number;
y: number;
width: number;
height: number;
reason?: string;
}>;
selectors?: Array<{
selector: string;
reason?: string;
}>;
patterns?: Array<{
name: string;
bounds: { x: number; y: number; width: number; height: number };
}>;
}All async methods may throw errors. Common error types:
Thrown when ImageMagick operations fail.
try {
await processor.alignImages(ref, target, output);
} catch (error) {
if (error.message.includes('ImageMagick')) {
console.error('ImageMagick not installed');
}
}Thrown when input validation fails.
try {
await processor.generateDiff('', '', 'output.png');
} catch (error) {
if (error.message.includes('Invalid')) {
console.error('Invalid input paths');
}
}Thrown when file operations fail.
try {
await batchProcessor.processBatch('./missing', './dir', options);
} catch (error) {
if (error.code === 'ENOENT') {
console.error('Directory not found');
}
}- Always handle errors - Image processing can fail for various reasons
- Use appropriate thresholds - Too low may cause false positives
- Enable classification - Provides valuable insights into changes
- Configure exclusions - Ignore dynamic content like timestamps
- Use smart pairing - For better batch processing results
- Embed metadata - For traceability and debugging
- Clean up temp files - Use try/finally blocks for cleanup