forked from rsmbl/Resemble.js
-
Notifications
You must be signed in to change notification settings - Fork 37
/
resemble.js
601 lines (481 loc) · 13.8 KB
/
resemble.js
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/*
James Cryer / Huddle 2014
URL: https://github.com/Huddle/Resemble.js
*/
'use strict';
const PNG = require('pngjs').PNG;
const fs = require('fs');
const jpeg = require('jpeg-js');
//keeping wrong indentation and '_this' for better diff with origin resemble.js
let _this = {};
let pixelTransparency = 1;
let errorPixelColor = { // Color for Error Pixels. Between 0 and 255.
red: 255,
green: 0,
blue: 255,
alpha: 255
};
let errorPixelTransform = {
flat : function (d1, d2){
return {
r: errorPixelColor.red,
g: errorPixelColor.green,
b: errorPixelColor.blue,
a: errorPixelColor.alpha
}
},
movement: function (d1, d2){
return {
r: ((d2.r*(errorPixelColor.red/255)) + errorPixelColor.red)/2,
g: ((d2.g*(errorPixelColor.green/255)) + errorPixelColor.green)/2,
b: ((d2.b*(errorPixelColor.blue/255)) + errorPixelColor.blue)/2,
a: d2.a
}
}
};
let errorPixelTransformer = errorPixelTransform.flat;
let largeImageThreshold = 1200;
_this['resemble'] = function( fileData ){
let data = {};
let images = [];
let updateCallbackArray = [];
let tolerance = { // between 0 and 255
red: 16,
green: 16,
blue: 16,
alpha: 16,
minBrightness: 16,
maxBrightness: 240
};
let ignoreAntialiasing = false;
let ignoreColors = false;
let ignoreRectangles = null;
function triggerDataUpdate(){
let len = updateCallbackArray.length;
let i;
for(i=0;i<len;i++){
if (typeof updateCallbackArray[i] === 'function'){
updateCallbackArray[i](data);
}
}
}
function loop(x, y, callback){
let i,j;
for (i=0;i<x;i++){
for (j=0;j<y;j++){
callback(i, j);
}
}
}
function parseImage(sourceImageData, width, height){
let pixleCount = 0;
let redTotal = 0;
let greenTotal = 0;
let blueTotal = 0;
let brightnessTotal = 0;
loop(height, width, function(verticalPos, horizontalPos){
let offset = (verticalPos*width + horizontalPos) * 4;
let red = sourceImageData[offset];
let green = sourceImageData[offset + 1];
let blue = sourceImageData[offset + 2];
let brightness = getBrightness(red,green,blue);
pixleCount++;
redTotal += red / 255 * 100;
greenTotal += green / 255 * 100;
blueTotal += blue / 255 * 100;
brightnessTotal += brightness / 255 * 100;
});
data.red = Math.floor(redTotal / pixleCount);
data.green = Math.floor(greenTotal / pixleCount);
data.blue = Math.floor(blueTotal / pixleCount);
data.brightness = Math.floor(brightnessTotal / pixleCount);
triggerDataUpdate();
}
function loadImageData( fileData, callback ){
if (Buffer.isBuffer(fileData)) {
let png = new PNG();
png.parse(fileData, function (err, data) {
callback(data, data.width, data.height);
});
} else {
let ext = fileData.substring(fileData.lastIndexOf(".")+1);
if(ext=="png") {
let png = new PNG();
fs.createReadStream(fileData)
.pipe(png)
.on('parsed', function() {
callback(this, this.width, this.height);
});
}
if(ext=="jpg" || ext=="jpeg") {
let jpegData = fs.readFileSync(fileData);
fileData = jpeg.decode(jpegData, true);
callback(fileData, fileData.width, fileData.height);
}
};
}
function isColorSimilar(a, b, color){
let absDiff = Math.abs(a - b);
if(typeof a === 'undefined'){
return false;
}
if(typeof b === 'undefined'){
return false;
}
if(a === b){
return true;
} else if ( absDiff < tolerance[color] ) {
return true;
} else {
return false;
}
}
function isNumber(n) {
return !isNaN(parseFloat(n));
}
function isPixelBrightnessSimilar(d1, d2){
let alpha = isColorSimilar(d1.a, d2.a, 'alpha');
let brightness = isColorSimilar(d1.brightness, d2.brightness, 'minBrightness');
return brightness && alpha;
}
function getBrightness(r,g,b){
return 0.3*r + 0.59*g + 0.11*b;
}
function isRGBSame(d1,d2){
let red = d1.r === d2.r;
let green = d1.g === d2.g;
let blue = d1.b === d2.b;
return red && green && blue;
}
function isRGBSimilar(d1, d2){
let red = isColorSimilar(d1.r,d2.r,'red');
let green = isColorSimilar(d1.g,d2.g,'green');
let blue = isColorSimilar(d1.b,d2.b,'blue');
let alpha = isColorSimilar(d1.a, d2.a, 'alpha');
return red && green && blue && alpha;
}
function isContrasting(d1, d2){
return Math.abs(d1.brightness - d2.brightness) > tolerance.maxBrightness;
}
function getHue(r,g,b){
r = r / 255;
g = g / 255;
b = b / 255;
let max = Math.max(r, g, b), min = Math.min(r, g, b);
let h;
let d;
if (max == min){
h = 0; // achromatic
} else{
d = max - min;
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return h;
}
function isAntialiased(sourcePix, data, cacheSet, verticalPos, horizontalPos, width){
let offset;
let targetPix;
let distance = 1;
let i;
let j;
let hasHighContrastSibling = 0;
let hasSiblingWithDifferentHue = 0;
let hasEquivilantSibling = 0;
addHueInfo(sourcePix);
for (i = distance*-1; i <= distance; i++){
for (j = distance*-1; j <= distance; j++){
if(i===0 && j===0){
// ignore source pixel
} else {
offset = ((verticalPos+j)*width + (horizontalPos+i)) * 4;
targetPix = getPixelInfo(data, offset, cacheSet);
if(targetPix === null){
continue;
}
addBrightnessInfo(targetPix);
addHueInfo(targetPix);
if( isContrasting(sourcePix, targetPix) ){
hasHighContrastSibling++;
}
if( isRGBSame(sourcePix,targetPix) ){
hasEquivilantSibling++;
}
if( Math.abs(targetPix.h - sourcePix.h) > 0.3 ){
hasSiblingWithDifferentHue++;
}
if( hasSiblingWithDifferentHue > 1 || hasHighContrastSibling > 1){
return true;
}
}
}
}
if(hasEquivilantSibling < 2){
return true;
}
return false;
}
function errorPixel(px, offset, data1, data2){
let data = errorPixelTransformer(data1, data2);
px[offset] = data.r;
px[offset + 1] = data.g;
px[offset + 2] = data.b;
px[offset + 3] = data.a;
}
function copyPixel(px, offset, data){
px[offset] = data.r; //r
px[offset + 1] = data.g; //g
px[offset + 2] = data.b; //b
px[offset + 3] = data.a * pixelTransparency; //a
}
function copyGrayScalePixel(px, offset, data){
px[offset] = data.brightness; //r
px[offset + 1] = data.brightness; //g
px[offset + 2] = data.brightness; //b
px[offset + 3] = data.a * pixelTransparency; //a
}
function getPixelInfo(data, offset, cacheSet){
let r;
let g;
let b;
let d;
let a;
r = data[offset];
if(typeof r !== 'undefined'){
g = data[offset+1];
b = data[offset+2];
a = data[offset+3];
d = {
r: r,
g: g,
b: b,
a: a
};
return d;
} else {
return null;
}
}
function addBrightnessInfo(data){
data.brightness = getBrightness(data.r,data.g,data.b); // 'corrected' lightness
}
function addHueInfo(data){
data.h = getHue(data.r,data.g,data.b);
}
function analyseImages(img1, img2, width, height){
let data1 = img1.data;
let data2 = img2.data;
//TODO
let imgd = new PNG({
width: img1.width,
height: img1.height,
deflateChunkSize: img1.deflateChunkSize,
deflateLevel: img1.deflateLevel,
deflateStrategy: img1.deflateStrategy,
});
let targetPix = imgd.data;
let mismatchCount = 0;
let time = Date.now();
let skip;
let currentRectangle = null;
let rectagnlesIdx = 0;
if(!!largeImageThreshold && ignoreAntialiasing && (width > largeImageThreshold || height > largeImageThreshold)){
skip = 6;
}
loop(height, width, function(verticalPos, horizontalPos){
let offset = (verticalPos*width + horizontalPos) * 4;
if(skip){ // only skip if the image isn't small
if(verticalPos % skip === 0 || horizontalPos % skip === 0){
copyPixel(targetPix, offset, {
r: 0,
b: 0,
g: 0,
a: 0
});
return;
}
}
let pixel1 = getPixelInfo(data1, offset, 1);
let pixel2 = getPixelInfo(data2, offset, 2);
if(pixel1 === null || pixel2 === null){
return;
}
if (ignoreRectangles) {
for(rectagnlesIdx = 0; rectagnlesIdx < ignoreRectangles.length; rectagnlesIdx++) {
currentRectangle = ignoreRectangles[rectagnlesIdx];
//console.log(currentRectangle, verticalPos, horizontalPos);
if (
(verticalPos >= currentRectangle[1]) &&
(verticalPos < currentRectangle[1] + currentRectangle[3]) &&
(horizontalPos >= currentRectangle[0]) &&
(horizontalPos < currentRectangle[0] + currentRectangle[2])
) {
copyGrayScalePixel(targetPix, offset, pixel2);
//copyPixel(targetPix, offset, pixel1, pixel2);
return;
}
}
}
if (ignoreColors){
addBrightnessInfo(pixel1);
addBrightnessInfo(pixel2);
if( isPixelBrightnessSimilar(pixel1, pixel2) ){
copyGrayScalePixel(targetPix, offset, pixel2);
} else {
errorPixel(targetPix, offset, pixel1, pixel2);
mismatchCount++;
}
return;
}
if( isRGBSimilar(pixel1, pixel2) ){
copyPixel(targetPix, offset, pixel1);
} else if( ignoreAntialiasing && (
addBrightnessInfo(pixel1), // jit pixel info augmentation looks a little weird, sorry.
addBrightnessInfo(pixel2),
isAntialiased(pixel1, data1, 1, verticalPos, horizontalPos, width) ||
isAntialiased(pixel2, data2, 2, verticalPos, horizontalPos, width)
)){
if( isPixelBrightnessSimilar(pixel1, pixel2) ){
copyGrayScalePixel(targetPix, offset, pixel2);
} else {
errorPixel(targetPix, offset, pixel1, pixel2);
mismatchCount++;
}
} else {
errorPixel(targetPix, offset, pixel1, pixel2);
mismatchCount++;
}
});
data.rawMisMatchPercentage = (mismatchCount / (height*width) * 100);
data.misMatchPercentage = data.rawMisMatchPercentage.toFixed(2);
data.analysisTime = Date.now() - time;
data.getDiffImage = function(text){
return imgd;
};
data.getDiffImageAsJPEG = function(quality) {
return jpeg.encode({
data: targetPix,
width: img1.width,
height: img1.height
}, quality !== undefined ? quality : 50).data;
};
}
function compare(one, two){
function onceWeHaveBoth(img){
let width;
let height;
images.push(img);
if(images.length === 2){
width = images[0].width > images[1].width ? images[0].width : images[1].width;
height = images[0].height > images[1].height ? images[0].height : images[1].height;
if( (images[0].width === images[1].width) && (images[0].height === images[1].height) ){
data.isSameDimensions = true;
} else {
data.isSameDimensions = false;
}
data.dimensionDifference = { width: images[0].width - images[1].width, height: images[0].height - images[1].height };
//lksv: normalization removed
analyseImages( images[0], images[1], width, height);
triggerDataUpdate();
}
}
images = [];
loadImageData(one, onceWeHaveBoth);
loadImageData(two, onceWeHaveBoth);
}
function getCompareApi(param){
let secondFileData,
hasMethod = typeof param === 'function';
if( !hasMethod ){
// assume it's file data
secondFileData = param;
}
let self = {
ignoreNothing: function(){
tolerance.red = 16;
tolerance.green = 16;
tolerance.blue = 16;
tolerance.alpha = 16;
tolerance.minBrightness = 16;
tolerance.maxBrightness = 240;
ignoreAntialiasing = false;
ignoreColors = false;
if(hasMethod) { param(); }
return self;
},
ignoreAntialiasing: function(){
tolerance.red = 32;
tolerance.green = 32;
tolerance.blue = 32;
tolerance.alpha = 32;
tolerance.minBrightness = 64;
tolerance.maxBrightness = 96;
ignoreAntialiasing = true;
ignoreColors = false;
if(hasMethod) { param(); }
return self;
},
ignoreColors: function(){
tolerance.alpha = 16;
tolerance.minBrightness = 16;
tolerance.maxBrightness = 240;
ignoreAntialiasing = false;
ignoreColors = true;
if(hasMethod) { param(); }
return self;
},
//array of rectangles, each rectangle is defined as (x, y, width. height)
//e.g. [[325, 170, 100, 40]]
ignoreRectangles: function(rectangles) {
ignoreRectangles = rectangles;
return self;
},
repaint: function(){
if(hasMethod) { param(); }
return self;
},
onComplete: function( callback ){
updateCallbackArray.push(callback);
let wrapper = function(){
compare(fileData, secondFileData);
};
wrapper();
return getCompareApi(wrapper);
}
};
return self;
}
return {
onComplete: function( callback ){
updateCallbackArray.push(callback);
loadImageData(fileData, function(imageData, width, height){
parseImage(imageData.data, width, height);
});
},
compareTo: function(secondFileData){
return getCompareApi(secondFileData);
}
};
};
_this['resemble'].outputSettings = function(options){
let key;
let undefined;
if(options.errorColor){
for (key in options.errorColor) {
errorPixelColor[key] = options.errorColor[key] === undefined ? errorPixelColor[key] : options.errorColor[key];
}
}
if(options.errorType && errorPixelTransform[options.errorType] ){
errorPixelTransformer = errorPixelTransform[options.errorType];
}
pixelTransparency = options.transparency || pixelTransparency;
if (options.largeImageThreshold !== undefined) {
largeImageThreshold = options.largeImageThreshold;
}
return this;
};
module.exports = _this['resemble']