resemble.js

repository·master·Indexed 26 days ago

https://github.com/rsmbl/resemble.js

A JavaScript library for image analysis and comparison using HTML5 Canvas. It supports detecting differences, handling antialiasing, and works in both browser and Node.js environments. Features include a fluent API for chaining configuration, a Promise-based API for Node.js, and tools for analyzing image brightness and color or comparing two images with customizable tolerances and output settings.

Tokens
2.6K
Snippets
6
Records
12
Agent score
39%

What's inside resemble.js

  1. Compare images in Node.js (Promise-based)

    master

    In Node.js, use the resemblejs/compareImages module for a Promise-based API. This is ideal for async/await workflows and works with file buffers.

    const compareImages = require("resemblejs/compareImages");
    const fs = require("mz/fs");
    
    async function getDiff() {
        const options = {
            output: {
                errorColor: {
                    red: 255,
                    green: 0,
                    blue: 255
                },
                errorType: "movement",
                transparency: 0.3,
                largeImageThreshold: 1200,
                useCrossOrigin: false,
                outputDiff: true
            },
            scaleToSameSize: true,
            ignore: "antialiasing"
        };
    
        const data = await compareImages(await fs.readFile("./your-image-path/People.jpg"), await fs.readFile("./your-image-path/People2.jpg"), options);
    
        await fs.writeFile("./output.png", data.getBuffer());
    }
    
    getDiff();
  2. Configure Node.js environment for Resemble.js

    master

    Resemble.js uses node-canvas for Node.js support.

    • For in-browser only: Skip the node-canvas dependency by running npm install --no-optional.
    • If node-canvas fails to install:
      • Use a previous version of Resemble.js.
      • Use NPM overrides to specify a more recent version of node-canvas.
      • Run npm install --build-from-source.
  3. Analyze a single image

    master

    Retrieve basic analysis (red, green, blue, and brightness) for a single image using the resemble() function and .onComplete() callback.

    var api = resemble(fileData).onComplete(function (data) {
        console.log(data);
        /*
        {
          red: 255,
          green: 255,
          blue: 255,
          brightness: 255
        }
        */
    });
  4. Compare two images

    master

    Use resemble(file).compareTo(file2) to compare two images. You can chain methods like .ignoreColors() and .onComplete() to handle the results. You can also use .scaleToSameSize() to ensure the second image matches the dimensions of the first, or .ignoreAntialiasing() to change the comparison method.

    var diff = resemble(file)
        .compareTo(file2)
        .ignoreColors()
        .onComplete(function (data) {
            console.log(data);
        });
    
    diff.scaleToSameSize();
    
    diff.ignoreAntialiasing();
  5. Configure global output settings

    master

    Use resemble.outputSettings() to configure how comparison results are displayed and processed. Note: This mutates global state and affects all subsequent Resemble calls.

    resemble.outputSettings({
        errorColor: {
            red: 255,
            green: 0,
            blue: 255
        },
        errorType: "movement",
        transparency: 0.3,
        largeImageThreshold: 1200,
        useCrossOrigin: false,
        outputDiff: true
    });
  6. Use the single callback API

    master

    The resemble.compare function provides a convenience wrapper for comparisons using a standard callback pattern.

    const compare = require("resemblejs").compare;
    
    function getDiff() {
        const options = {
            returnEarlyThreshold: 5
        };
    
        compare(image1, image2, options, function (err, data) {
            if (err) {
                console.log("An error!");
            } else {
                console.log(data);
            }
        });
    }
  7. Reference: outputSettings configuration options

    master

    The following options are available via resemble.outputSettings():

    • errorColor: An object {red, green, blue} defining the color used for errors.
    • errorType: The type of error display (e.g., "movement").
    • transparency: Float value for transparency.
    • largeImageThreshold: Threshold in pixels. If image width/height exceeds this, the algorithm skips pixels to improve performance. Set to 0 to disable this behavior.
    • useCrossOrigin: Boolean. Set to false if using Data URIs.
    • outputDiff: Boolean. Whether to output the difference image.
    • boundingBox: An object {left, top, right, bottom} to narrow the comparison area.
    • boundingBoxes: An array of bounding box objects.
    • ignoredBox: An object {left, top, right, bottom} to exclude an area from comparison.
    • ignoredBoxes: An array of ignored box objects.
    • ignoreAreasColoredWith: An object {r, g, b, a}. Pixels matching this color on the reference image will be excluded.
  8. Use the fluent API for image comparison

    master

    For more control, you can use the fluent API starting with resemble(image1). This allows you to chain configuration methods before calling compareTo(image2) and onComplete(callback).

    Available chainable methods on the resemble instance:

    • compareTo(secondFileData): Initiates comparison with a second image.
    • onComplete(callback): Registers the callback for when comparison finishes.
    • outputSettings(options): Configures how the diff image is generated.
    • scaleToSameSize(): Scales images to match the first image's size.
    • useOriginalSize(): Disables scaling (default behavior).
    • ignoreNothing(), ignoreLess(), ignoreAntialiasing(), ignoreColors(), ignoreAlpha(): Preset tolerance configurations.
    • setupCustomTolerance(customSettings): Manually sets tolerance values.
    • setReturnEarlyThreshold(threshold): Sets a percentage threshold to stop comparison early.

    Available chainable methods on the comparison object (returned by compareTo):

    • outputSettings(options)
    • scaleToSameSize()
    • useOriginalSize()
    • ignoreNothing(), ignoreLess(), ignoreAntialiasing(), ignoreColors(), ignoreAlpha()
    • setupCustomTolerance(customSettings)
    • setReturnEarlyThreshold(threshold)
  9. Configure global output settings

    master

    You can set global output settings that apply to all subsequent resemble calls using resemble.outputSettings(options). This is useful for setting a consistent errorColor or errorType across your application.

    Options for outputSettings:

    • errorColor: Object { red, green, blue, alpha } (0-255) to define the color used for error pixels.
    • errorType: String defining the error pixel transformation algorithm. Options: 'flat', 'movement', 'flatDifferenceIntensity', 'movementDifferenceIntensity', 'diffOnly'.
    • transparency: Number (0-1) for the transparency of the error pixels.
    • largeImageThreshold: Number to trigger optimization for large images.
    • useCrossOrigin: Boolean to enable/disable cross-origin requests.
    • boundingBoxes / ignoredBoxes: Arrays of objects { top, left, bottom, right } to include or exclude specific areas from comparison.
    • ignoreAreasColoredWith: An object { r, g, b, a } representing a color that should be ignored during comparison.
  10. Compare two images using resemble.compare()

    master

    The simplest way to compare two images is using the resemble.compare static method. It accepts two image sources (URLs, Buffers, or ImageData), an optional configuration object, and a callback function. The callback receives an error as the first argument and the comparison results as the second.

    Supported image sources:

    • Image URLs (strings)
    • Node.js Buffers
    • ImageData objects

    Common configuration options:

    • output: Object containing errorColor, errorType, transparency, boundingBoxes, ignoredBoxes, or ignoreAreasColoredWith.
    • ignore: A string (e.g., 'antialiasing', 'colors', 'alpha', 'nothing', 'less') or an array of these strings to define how much difference to ignore.
    • tolerance: Object to override specific tolerance values (e.g., red, green, blue, alpha, minBrightness, maxBrightness).
    • scaleToSameSize: Boolean to scale images to match dimensions.
    • returnEarlyThreshold: Number to stop comparison early if a certain mismatch percentage is reached.
  11. Access comparison results and diff images

    master

    The comparison result object (data) contains the following properties:

    • misMatchPercentage: A string representing the percentage of mismatched pixels (e.g., "1.23").
    • rawMisMatchPercentage: The numeric value of the mismatch percentage.
    • isSameDimensions: Boolean indicating if images have the same width and height.
    • dimensionDifference: Object { width, height } showing the difference in dimensions.
    • diffBounds: Object { top, left, bottom, right } defining the bounding box of the differences.
    • analysisTime: Time taken for the analysis in milliseconds.
    • error: If an error occurred during loading, this contains the error message.

    To retrieve the visual difference:

    • data.getImageDataUrl(text?): Returns a Base64 Data URL of the diff image. If text is provided, it adds a label to the top of the image.
    • data.getBuffer(includeOriginal?): Returns a Buffer of the diff image. If includeOriginal is true, it returns a buffer containing the original images and the diff side-by-side.