image-diff-rs

This project provides an image differencing library that supports PNG,JPEG,GIF,TIFF,and WebP formats for Node.js, Deno, and Rust.

MIT License

Downloads
43
Stars
13
Committers
2

image-diff-rs

This project provides an image differencing library that supports PNG,JPEG,GIF,TIFF,and WebP formats for Node.js, Deno, and Rust. For more details, please refer to each respective directory.

The code for Node.js and Deno is generated using wit-bindgen and jco.

Demo

img1 img2 diff

JavaScript

installation

npm install @bokuweb/image-diff-wasm

examples

import { readFile } from "node:fs/promises";
import { diff } from "@bokuweb/image-diff-wasm";

const imga = await readFile(PATH_TO_IMAGE_A);
const imgb = await readFile(PATH_TO_IMAGE_B);

const result = diff(imga, imgb, { enableAntiAlias: true, threshold: 0.01 });

API

diff(imga: Uint8Array, imgb: Uint8Array, opts: Opts): Output;

The diff function is designed to compare two images and identify their differences. It takes two image buffers as input and returns an Output object containing information about the differences.

Input
  • imga: Uint8Array: The first image buffer.
  • imgb: Uint8Array: The second image buffer.
  • opts: Opts: Options object for the function.
export interface Opts {
  threshold?: number,
  includeAntiAlias?: boolean,
}
  • threshold: Matching threshold, ranges from 0 to 1. Smaller values make the comparison more sensitive. 0.1 by default.
  • includeAntiAlias: The flag of antialias. If omitted false.
Output
export interface Output {
  diffCount: number,
  diffImage: Uint8Array,
  width: number,
  height: number,
}
  • diffCount: The number of pixels that differ between the two images.
  • diffImage: The buffer of the difference image in WebP format.
  • width: The width of the difference image.
  • height: The height of the difference image.
Error

The function may throw following values as ComponentError.

export type Error = ErrorDecode | ErrorEncode;
export interface ErrorDecode {
  tag: 'decode',
  val: string,
}
export interface ErrorEncode {
  tag: 'encode',
  val: string,
}

Rust

Installation

image-diff-rs = { git = "https://github.com/bokuweb/image-diff-rs.git" }

examples

pub fn main() {
    let imga = std::fs::read("../fixtures/sample0.webp").unwrap();
    let imgb = std::fs::read("../fixtures/sample1.webp").unwrap();

    let _result = diff(
        imga,
        imgb,
        &DiffOption {
            threshold: Some(0.01),
            include_anti_alias: Some(true),
        },
    )
    .unwrap();
}
cargo run --example compare

Wasm

Generate JS code from wasm component.

AR=llvm-ar CFLAGS='--sysroot ../wasi-sdk/share/wasi-sysroot' cargo wasi build --release
wasm-tools component new target/wasm32-wasi/release/image_diff_wasm.wasm -o wasm/component.wasm --adapt wasm/wasi_snapshot_preview1.wasm
jco transpile wasm/component.wasm -o js --name index && mv js/index.js js/index.mjs