MCPcopy Index your code
hub / github.com/BuilderIO/SSDiff / compare

Method compare

packages/ssdiff/src/index.ts:182–221  ·  view source on GitHub ↗

* Returns the pixel difference number for two images and creates a difference image * * @remarks * This is the main method for comparision of screenshots for a pathname on two domains. * * @param url1 - url of domain1 + pathnmae * @param url2 - url of domain2 + pathname * @param

(compareObj: { url1: any; url2: any; fileName: any })

Source from the content-addressed store, hash-verified

180 * @returns Pixel difference number for two images and creates a difference image
181 */
182 async compare(compareObj: { url1: any; url2: any; fileName: any }) {
183 try {
184 const { url1, url2, fileName } = compareObj;
185 const screenshots = await Promise.all([this.screenshot(url1), this.screenshot(url2)]);
186 // TODO: Make the file name dynamic based on the fileType in screenshotConfig
187 let image1 = PNG.sync.read(screenshots[0]);
188 let image2 = PNG.sync.read(screenshots[1]);
189 const maxHeight = Math.max(image1.height, image2.height);
190 const maxWidth = Math.max(image1.width, image2.width);
191 if (image1.height !== image2.height || image1.width !== image2.width) {
192 if (this.failInCaseOfDifferentSize) {
193 this.log(`Failed due to different sized image for pathname : /${fileName}`);
194 throw new Error(`Images are of different sizes for pathname : /${fileName}`);
195 }
196 // images needs to be resized before comparision
197 this.log(`Resizing images for pathname : /${fileName}`);
198 image1 = await this.resizeImage(image1, maxWidth, maxHeight);
199 image2 = await this.resizeImage(image2, maxWidth, maxHeight);
200 this.log(`Resized images for ${fileName}...`);
201 }
202 const diff = new PNG({ width: maxWidth, height: maxHeight });
203 const numDiffPixels = pixelmatch(image1.data, image2.data, diff.data, maxWidth, maxHeight, {
204 threshold: 0.1,
205 includeAA: true,
206 diffColor: [253, 225, 225],
207 diffColorAlt: [212, 143, 143],
208 });
209 const totalPixels = diff.data.length / 4;
210 const differencePercentage = (numDiffPixels / totalPixels) * 100;
211 this.log(
212 `file name: ${fileName} | numDiffPixels: ${numDiffPixels} | height: ${maxHeight} | width: ${maxWidth} | totalPixels: ${totalPixels} | percentage: ${
213 (numDiffPixels / totalPixels) * 100
214 }}`,
215 );
216 this.fileNameDifferenceMap.set(fileName, differencePercentage); // this map is used to sort the files in the folde
217 fs.writeFileSync(this.diffScreenshots + `/${fileName}`, PNG.sync.write(diff));
218 } catch (e: any) {
219 throw new Error("Error while comparing screenshots: " + e.message);
220 }
221 }
222 async sortFilesBasedOnDifference() {
223 const sortedMap = new Map([...this.fileNameDifferenceMap.entries()].sort((a, b) => b[1] - a[1]));
224 return sortedMap;

Callers 1

resultMethod · 0.95

Calls 3

screenshotMethod · 0.95
logMethod · 0.95
resizeImageMethod · 0.95

Tested by

no test coverage detected