This repository has been archived by the owner on Dec 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
images.ts
365 lines (332 loc) · 12.9 KB
/
images.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import {red, yellow} from 'chalk';
import {access, copySync, outputFile, readFileSync} from 'fs-extra';
import {join} from 'path';
import compareImages from '../resemble/compareImages';
import {calculateDprData, getAndCreatePath, getScreenshotSize} from '../helpers/utils';
import {DEFAULT_RESIZE_DIMENSIONS} from '../helpers/constants';
import {determineStatusAddressToolBarRectangles} from './rectangles';
import {RectanglesOutput} from './rectangles.interfaces';
import {
CompareOptions, CroppedBase64Image,
IgnoreBoxes,
ImageCompareOptions,
ImageCompareResult,
ResizeDimensions
} from './images.interfaces';
import {FullPageScreenshotsData} from './screenshots.interfaces';
import {Executor} from './methods.interface';
import {CompareData} from '../resemble/compare.interfaces';
import {LogLevel} from "../helpers/options.interface";
const {createCanvas, loadImage} = require('canvas');
/**
* Check if the image exists and create a new baseline image if needed
*/
export async function checkBaselineImageExists(
actualFilePath: string,
baselineFilePath: string,
autoSaveBaseline: boolean,
logLevel: LogLevel,
): Promise<void> {
return new Promise((resolve, reject) => {
access(baselineFilePath, error => {
if (error) {
if (autoSaveBaseline) {
try {
copySync(actualFilePath, baselineFilePath);
if (logLevel === LogLevel.info) {
console.log(yellow(`
#####################################################################################
INFO:
Autosaved the image to
${baselineFilePath}
#####################################################################################
`));
}
} catch (error) {
/* istanbul ignore next */
reject(red(`
#####################################################################################
Image could not be copied. The following error was thrown:
${error}
#####################################################################################
`));
}
} else {
reject(red(`
#####################################################################################
Baseline image not found, save the actual image manually to the baseline.
The image can be found here:
${actualFilePath}
If you want the module to auto save a non existing image to the baseline you
can provide 'autoSaveBaseline: true' to the options.
#####################################################################################
`));
}
}
resolve();
});
});
}
/**
* Make a cropped image with Canvas
*/
export async function makeCroppedBase64Image({
base64Image,
rectangles,
logLevel,
resizeDimensions = DEFAULT_RESIZE_DIMENSIONS,
}: CroppedBase64Image): Promise<string> {
/**
* This is in for backwards compatibility, it will be removed in the future
*/
let resizeValues;
if (typeof resizeDimensions === 'number') {
resizeValues = {
top: resizeDimensions,
right: resizeDimensions,
bottom: resizeDimensions,
left: resizeDimensions,
};
if (logLevel === LogLevel.debug || logLevel === LogLevel.warn) {
console.log(yellow(`
#####################################################################################
WARNING:
THE 'resizeDimensions' NEEDS TO BE AN OBJECT LIKE
{
top: 10,
right: 20,
bottom: 15,
left: 25,
}
NOW IT WILL BE DEFAULTED TO
{
top: ${resizeDimensions},
right: ${resizeDimensions},
bottom: ${resizeDimensions},
left: ${resizeDimensions},
}
THIS IS DEPRACATED AND WILL BE REMOVED IN A NEW MAJOR RELEASE
#####################################################################################
`));
}
} else {
resizeValues = resizeDimensions;
}
const {top, right, bottom, left} = {...DEFAULT_RESIZE_DIMENSIONS, ...resizeValues};
const {height, width, x, y} = rectangles;
const canvasWidth = width + left + right;
const canvasHeight = height + top + bottom;
const canvas = createCanvas(canvasWidth, canvasHeight);
const image = await loadImage(`data:image/png;base64,${base64Image}`);
const ctx = canvas.getContext('2d');
let sourceXStart = x - left;
let sourceYStart = y - top;
if (sourceXStart < 0) {
if (logLevel === LogLevel.debug || logLevel === LogLevel.warn) {
console.log(yellow(`
#####################################################################################
THE RESIZE DIMENSION LEFT '${left}' MADE THE CROPPING GO OUT OF
THE IMAGE BOUNDARIES RESULTING IN AN IMAGE STARTPOSITION '${sourceXStart}'.
THIS HAS BEEN DEFAULTED TO '0'
#####################################################################################
`));
}
sourceXStart = 0;
}
if (sourceYStart < 0) {
if (logLevel === LogLevel.debug || logLevel === LogLevel.warn) {
console.log(yellow(`
#####################################################################################
THE RESIZE DIMENSION LEFT '${top}' MADE THE CROPPING GO OUT OF
THE IMAGE BOUNDARIES RESULTING IN AN IMAGE STARTPOSITION '${sourceYStart}'.
THIS HAS BEEN DEFAULTED TO '0'
#####################################################################################
`));
}
sourceYStart = 0;
}
ctx.drawImage(image,
// Start at x/y pixels from the left and the top of the image (crop)
sourceXStart, sourceYStart,
// 'Get' a (w * h) area from the source image (crop)
canvasWidth, canvasHeight,
// Place the result at 0, 0 in the canvas,
0, 0,
// With as width / height: 100 * 100 (scale)
canvasWidth, canvasHeight
);
return canvas.toDataURL().replace(/^data:image\/png;base64,/, '');
}
/**
* Execute the image compare
*/
export async function executeImageCompare(
executor: Executor,
options: ImageCompareOptions,
isViewPortScreenshot: boolean = false,
): Promise<ImageCompareResult | number> {
// 1. Set some variables
const {devicePixelRatio, fileName, isAndroidNativeWebScreenshot, isHybridApp, logLevel, platformName} = options;
const {
actualFolder,
autoSaveBaseline,
baselineFolder,
browserName,
deviceName,
diffFolder,
isMobile,
savePerInstance,
} = options.folderOptions;
let diffFilePath;
const imageCompareOptions = {...options.compareOptions.wic, ...options.compareOptions.method};
// 2. Create all needed folders
const createFolderOptions = {browserName, deviceName, isMobile, savePerInstance};
const actualFolderPath = getAndCreatePath(actualFolder, createFolderOptions);
const baselineFolderPath = getAndCreatePath(baselineFolder, createFolderOptions);
const actualFilePath = join(actualFolderPath, fileName);
const baselineFilePath = join(baselineFolderPath, fileName);
// 3. Check if there is a baseline image, and determine if it needs to be auto saved or not
await checkBaselineImageExists(actualFilePath, baselineFilePath, autoSaveBaseline, logLevel);
// 4. Prepare the compare
// 4a. Determine the ignore options
const resembleIgnoreDefaults = ['alpha', 'antialiasing', 'colors', 'less', 'nothing'];
const ignore = resembleIgnoreDefaults.filter(option =>
Object.keys(imageCompareOptions).find(key =>
// @ts-ignore
key.toLowerCase().includes(option) && imageCompareOptions[key]
));
// 4b. Determine the ignore rectangles for the blockouts
const blockOut = 'blockOut' in imageCompareOptions ? imageCompareOptions.blockOut : [];
const statusAddressToolBarOptions = {
isHybridApp,
isMobile,
isViewPortScreenshot,
platformName,
isAndroidNativeWebScreenshot,
blockOutStatusBar: imageCompareOptions.blockOutStatusBar,
blockOutToolBar: imageCompareOptions.blockOutToolBar,
};
const ignoredBoxes = blockOut.concat(
// 4c. Add the mobile rectangles that need to be ignored
await determineStatusAddressToolBarRectangles(executor, statusAddressToolBarOptions)
).map(
// 4d. Make sure all the rectangles are equal to the dpr for the screenshot
rectangles => {
return calculateDprData({
// Adjust for the ResembleJS API
bottom: rectangles.y + rectangles.height,
right: rectangles.x + rectangles.width,
left: rectangles.x,
top: rectangles.y,
}, devicePixelRatio);
}
);
const compareOptions: CompareOptions = {
ignore,
...(ignoredBoxes.length > 0 ? {output: {ignoredBoxes}} : {}),
scaleToSameSize: imageCompareOptions.scaleImagesToSameSize,
};
// 5. Execute the compare and retrieve the data
const data: CompareData = await compareImages(readFileSync(baselineFilePath), readFileSync(actualFilePath), compareOptions);
const misMatchPercentage = imageCompareOptions.rawMisMatchPercentage
? data.rawMisMatchPercentage
: Number(data.rawMisMatchPercentage.toFixed(2));
// 6. Save the diff when there is a diff or when debug mode is on
if (misMatchPercentage > imageCompareOptions.saveAboveTolerance || logLevel === LogLevel.debug) {
const isDifference = misMatchPercentage > imageCompareOptions.saveAboveTolerance;
const isDifferenceMessage = 'WARNING:\n There was a difference. Saved the difference to';
const debugMessage = 'INFO:\n Debug mode is enabled. Saved the debug file to:';
const diffFolderPath = getAndCreatePath(diffFolder, createFolderOptions);
diffFilePath = join(diffFolderPath, fileName);
await saveBase64Image(
await addBlockOuts(Buffer.from(data.getBuffer()).toString('base64'), ignoredBoxes),
diffFilePath,
);
if (logLevel === LogLevel.debug || logLevel === LogLevel.warn) {
console.log(yellow(`
#####################################################################################
${isDifference ? isDifferenceMessage : debugMessage}
${diffFilePath}
#####################################################################################
`));
}
}
// 7. Return the comparison data
return imageCompareOptions.returnAllCompareData ? {
fileName,
folders: {
actual: actualFilePath,
baseline: baselineFilePath,
...(diffFilePath ? {diff: diffFilePath} : {}),
},
misMatchPercentage,
} : misMatchPercentage;
}
/**
* Make a full page image with Canvas
*/
export async function makeFullPageBase64Image(screenshotsData: FullPageScreenshotsData): Promise<string> {
const amountOfScreenshots = screenshotsData.data.length;
const {fullPageHeight: canvasHeight, fullPageWidth: canvasWidth} = screenshotsData;
const canvas = createCanvas(canvasWidth, canvasHeight);
const ctx = canvas.getContext('2d');
// Load all the images
for (let i = 0; i < amountOfScreenshots; i++) {
const {canvasYPosition, imageHeight, imageWidth, imageYPosition} = screenshotsData.data[i];
const image = await loadImage(`data:image/png;base64,${screenshotsData.data[i].screenshot}`);
ctx.drawImage(image,
// Start at x/y pixels from the left and the top of the image (crop)
0, imageYPosition,
// 0, 0,
// 'Get' a (w * h) area from the source image (crop)
imageWidth, imageHeight,
// Place the result at 0, 0 in the canvas,
0, canvasYPosition,
// With as width / height: 100 * 100 (scale)
imageWidth, imageHeight,
);
}
return canvas.toDataURL().replace(/^data:image\/png;base64,/, '');
}
/**
* Save the base64 image to a file
*/
export async function saveBase64Image(base64Image: string, filePath: string): Promise<void> {
return outputFile(filePath, base64Image, 'base64');
}
/**
* Create a canvas with the ignore boxes if they are present
*/
export async function addBlockOuts(screenshot: string, ignoredBoxes: IgnoreBoxes[]): Promise<string> {
// Create canvas and load image
const {height, width} = getScreenshotSize(screenshot);
const canvas = createCanvas(width, height);
const image = await loadImage(`data:image/png;base64,${screenshot}`);
const canvasContext = canvas.getContext('2d');
// Draw the image on canvas
canvasContext.drawImage(
image,
// Start at x/y pixels from the left and the top of the image (crop)
0, 0,
// 'Get' a (w * h) area from the source image (crop)
width, height,
// Place the result at 0, 0 in the canvas,
0, 0,
// With as width / height: 100 * 100 (scale)
width, height,
);
// Loop over all ignored areas and add them to the current canvas
ignoredBoxes.forEach(ignoredBox => {
const {right: ignoredBoxWidth, bottom: ignoredBoxHeight, left: x, top: y} = ignoredBox;
const ignoreCanvas = createCanvas(ignoredBoxWidth - x, ignoredBoxHeight - y);
const ignoreContext = ignoreCanvas.getContext('2d');
// Add a background color to the ignored box
ignoreContext.globalAlpha = 0.5;
ignoreContext.fillStyle = '#39aa56';
ignoreContext.fillRect(0, 0, ignoredBoxWidth - x, ignoredBoxHeight - y);
// add to canvasContext
canvasContext.drawImage(ignoreCanvas, x, y);
});
// Return the screenshot
return canvas.toDataURL().replace(/^data:image\/png;base64,/, '');
}