diff --git a/README.md b/README.md index b4402f7a..97f58a26 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ Create image differential between two images. expectedFilename: string; diffFilename?: string; options?: { + preprocess?: ([Image, Image]) => void | Promise<[Image, Image]>; threshold?: number; // default 0.1 includeAA?: boolean; // default false } @@ -51,7 +52,18 @@ Create image differential between two images. - `actualFilename` - *Required* - Path to actual image file. - `expectedFilename` - *Required* - Path to expected image file. - `diffFilename` - *Optional* - Path to differential image file. If omitted, `imgDiff` does not output image file. -- `options` - *Optional* - An object to pass through [pixelmatch](https://github.com/mapbox/pixelmatch#api). +- `options` - *Optional* +- `options.preprocess` - *Optional* - Preprocess function. It's called with decoded images and also can process them. +- `options.threshold`, `options.includeAA` - *Optional* - Parameters using by [pixelmatch](https://github.com/mapbox/pixelmatch#api). + +#### `Image` +```ts +{ + width: number; + height: number; + data: Uint8Array; +} +``` #### `ImgDiffResult` diff --git a/lib/index.js b/lib/index.js index 6d137359..fb3b98cc 100644 --- a/lib/index.js +++ b/lib/index.js @@ -68,7 +68,19 @@ function imgDiff(opt) { decode(opt.actualFilename), decode(opt.expectedFilename), ]).then(imgs => { - return compare(imgs[0], imgs[1], opt.diffFilename, opt.options); + const options = opt.options || { }; + let pp; + if (options.preprocess && typeof options.preprocess === "function") { + const ret = options.preprocess(imgs); + if (typeof ret === "object" && ret.then) { + pp = ret; + } else { + pp = Promise.resolve(imgs); + } + } else { + pp = Promise.resolve(imgs); + } + return pp.then(imgs => compare(imgs[0], imgs[1], opt.diffFilename, options)); }) ; } diff --git a/test/index.test.js b/test/index.test.js index 9091a7cc..0b8a97ed 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -61,3 +61,32 @@ test("compare with 2 jpeg files", async t => { }); t.truthy(fs.statSync(path.resolve(__dirname, "images/diff_generated.jpg.png"))); }); + +test("call preprocess hook", async t => { + let called = false; + await imgDiff({ + actualFilename: path.resolve(__dirname, "images/expected.png"), + expectedFilename: path.resolve(__dirname, "images/expected.png"), + options: { + preprocess: ([img1, img2]) => { + called = !!img1 && !!img2; + }, + }, + }); + t.is(called, true); +}); + +test("call preprocess hook with promiss", async t => { + let called = false; + await imgDiff({ + actualFilename: path.resolve(__dirname, "images/expected.png"), + expectedFilename: path.resolve(__dirname, "images/expected.png"), + options: { + preprocess: ([img1, img2]) => { + called = !!img1 && !!img2; + return Promise.resolve([img2, img1]); + }, + }, + }); + t.is(called, true); +});