All files / lib image.js

97.85% Statements 228/233
83.33% Branches 55/66
100% Functions 33/33
98.16% Lines 213/217

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                            1x   1x 1x 1x 1x 1x 1x   1x   1x   66x 20x   46x 46x 46x   46x 46x   46x   46x 46x                   1x 17x   17x 17x 17x   17x 17x 17x 17x     1x                     1x 2x   2x 2x 2x   2x   2x 2x 2x 3x       1x       1x                   1x 2x   2x 2x 2x   2x 2x 2x 2x       1x       1x                   1x 2x   2x 2x 2x   2x 2x 2x 2x       1x       1x                             1x   4x 4x 4x   4x 4x   4x 4x 4x   4x       4x 4x 4x   4x   4x 2x 2x           2x 2x                               1x   2x 2x 2x   2x 2x 2x   2x         2x 2x 2x     2x 2x 2x 2x     2x       2x   2x 2x 2x 2x 2x 2x                                 1x   32x 32x 32x 32x 32x 32x 32x   32x                                     1x 2x                         1x   4x 4x     4x 4x 4x 4x   4x             4x 4x   4x   4x 2084x   4814208x   4814208x   2x 2x 2x 2x 2x     2x     2x                   1x   5x 5x 5x       5x 76x   76x 6340x 6339x         5x                         1x   4814209x 4814209x         4814209x 1657800884x 1657800884x   1657800884x 892342288x   765458596x 765458596x   3x                     1x 6342x                     1x 1657800886x 1657800886x 1657800886x   1657800886x                         1x 20x 20x 20x     20x 28725x 28725x   28725x 78684673x               20x                   1x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x                   1x   20x 20x 20x 20x     20x 17338x   17338x 24x 30x 20x 20x         17338x 17334x   20x                 1x   10x 10x 10x     10x     10x 8668x   8668x 17369476x     10x     1x  
"use strict";
/**
 * Creates new instance of Image.
 *
 * @class
 * @name Image
 * @arg {string} srcPath - path to processed image
 * @arg {object} [srcOpts] - image options
 * @arg {number} [srcOpts.scaleX=1] - image current scale value on `X` axis
 * @arg {number} [srcOpts.scaleY=1] - image current scale value on `Y` axis
 * @arg {object} [injects] - Dependency injections.
 * @arg {object} [injects.sharp] - Injected `sharp` module.
 */
 
var fs = require("fs");
 
var _ = require("lodash");
var pixelmatch = require("pixelmatch");
var PNG = require("pngjs").PNG;
var sharp = require("sharp");
var temp = require("temp").track();
var U = require("glace-utils");
 
sharp.cache(false);
 
var Image = function (srcPath, srcOpts, injects) {
 
    if (!(this instanceof Image))
        return new Image(srcPath, srcOpts);
 
    srcOpts = U.defVal(srcOpts, {});
    srcOpts.scaleX = U.defVal(srcOpts.scaleX, 1);
    srcOpts.scaleY = U.defVal(srcOpts.scaleY, 1);
 
    this._srcPath = srcPath;
    this._srcOpts = srcOpts;
 
    this._pixelDenominator = 255 * Math.sqrt(3);
 
    injects = U.defVal(injects, {});
    this.__sharp = U.defVal(injects.sharp, sharp);
};
/**
 * Defines whether processed image is transparent.
 *
 * @async
 * @method
 * @return {Promise<boolean>} - `true` if image is transparent, `false`
 *  otherwise.
 */
Image.prototype.isTransparent = function () {
    return this._loadImg(this._srcPath, this._srcOpts).then(image => {
 
        var pixels = this._getPixels(image);
        var height = pixels.length;
        var width = pixels[0].length;
 
        for (var y = 0; y < height; y++) {
            var row = pixels[y];
            for (var x = 0; x < width; x++) {
                if (row[x].A !== 0) return false;
            };
        };
        return true;
    });
};
/**
 * Defines whether processed image is monochrome.
 *
 * @async
 * @method
 * @return {Promise<boolean>} - `true` if image is monochrome, `false`
 *  otherwise.
 */
Image.prototype.isMonochrome = function () {
    return this._loadImg(this._srcPath, this._srcOpts).then(image => {
 
        var pixels = this._getPixels(image);
        var height = pixels.length;
        var width = pixels[0].length;
 
        var firstPixel = pixels[0][0];
 
        for (var y = 0; y < height; y++) {
            var row = pixels[y];
            for (var x = 0; x < width; x++) {
                if (row[x].A !== firstPixel.A ||
                        row[x].R !== firstPixel.R ||
                        row[x].G !== firstPixel.G ||
                        row[x].B !== firstPixel.B) {
                    return false;
                };
            };
        };
        return true;
    });
};
/**
 * Defines whether processed image is black.
 *
 * @async
 * @method
 * @return {Promise<boolean>} - `true` if image is black, `false` otherwise.
 */
Image.prototype.isBlack = function () {
    return this._loadImg(this._srcPath, this._srcOpts).then(image => {
 
        var pixels = this._getPixels(image);
        var height = pixels.length;
        var width = pixels[0].length;
 
        for (var y = 0; y < height; y++) {
            var row = pixels[y];
            for (var x = 0; x < width; x++) {
                if (row[x].A !== 255 ||
                        row[x].R !== 0 ||
                        row[x].G !== 0 ||
                        row[x].B !== 0) {
                    return false;
                };
            };
        };
        return true;
    });
};
/**
 * Defines whether processed image is white.
 *
 * @async
 * @method
 * @return {Promise<boolean>} - `true` if image is white, `false` otherwise.
 */
Image.prototype.isWhite = function () {
    return this._loadImg(this._srcPath, this._srcOpts).then(image => {
 
        var pixels = this._getPixels(image);
        var height = pixels.length;
        var width = pixels[0].length;
 
        for (var y = 0; y < height; y++) {
            var row = pixels[y];
            for (var x = 0; x < width; x++) {
                if (row[x].A !== 255 ||
                        row[x].R !== 255 ||
                        row[x].G !== 255 ||
                        row[x].B !== 255) {
                    return false;
                };
            };
        };
        return true;
    });
};
/**
 * Defines if processed image includes specified image.
 *
 * @method
 * @arg {string} dstPath - path to potentially included image
 * @arg {object} [dstOpts] - included image options
 * @arg {number} [dstOpts.tolerance=0.05] - comparison tolerance
 * @arg {?string} [dstOpts.matchedPath=null] - path to same captured place
 * @arg {boolean} [dstOpts.saveMatch=false] - flag to capture images
 *  intersection or no
 * @return {Promise<object>} - result
 */
Image.prototype.includes = function (dstPath, dstOpts) {
 
    dstOpts = U.defVal(dstOpts, {});
    dstOpts.scaleX = U.defVal(dstOpts.scaleX, 1);
    dstOpts.scaleY = U.defVal(dstOpts.scaleY, 1);
 
    this._dstPath = dstPath;
    this._dstOpts = dstOpts;
 
    this._tolerance = U.defVal(dstOpts.tolerance, .05);
    this._matchedPath = U.defVal(dstOpts.matchedPath);
    this._saveMatch = U.defVal(dstOpts.saveMatch, !!this._matchedPath);
 
    Iif (this._saveMatch && !this._matchedPath)
        this._matchedPath = temp.path({ suffix: ".png" });
 
    var srcImage;
    return this._loadImg(this._srcPath, this._srcOpts).then(image => {
        srcImage = image;
        return this._loadImg(this._dstPath, this._dstOpts);
    }).then(dstImage => {
        return this._includes(srcImage, dstImage);
    }).then(result => {
        if (!result.isIncluded) return { isIncluded: false };
        Iif (!this._saveMatch) return result;
        return this
            ._saveMatchImage(result.offsetX,
                result.offsetY,
                result.width,
                result.height)
            .then(() => {
                result.matchedPath = this._matchedPath;
                return result;
            });
    });
};
/**
 * Defines if processed image equal to specified image.
 *
 * @method
 * @arg {string} dstPath - path to potentially equal image
 * @arg {object} [dstOpts] - included image options
 * @arg {number} [dstOpts.tolerance=0.05] - comparison tolerance
 * @arg {?string} [dstOpts.diffPath=null] - path to save captured difference.
 * @arg {boolean} [dstOpts.saveDiff=false] - flag to capture images
 *  intersection or no
 * @return {Promise<number>} Ratio of difference.
 */
Image.prototype.equalTo = function (dstPath, dstOpts) {
 
    dstOpts = U.defVal(dstOpts, {});
    dstOpts.scaleX = U.defVal(dstOpts.scaleX, 1);
    dstOpts.scaleY = U.defVal(dstOpts.scaleY, 1);
 
    var tolerance = U.defVal(dstOpts.tolerance, .05);
    var diffPath = U.defVal(dstOpts.diffPath);
    var saveDiff = U.defVal(dstOpts.saveDiff, !!diffPath);
 
    Iif (saveDiff && !diffPath) {
        diffPath = temp.path({ suffix: ".png" });
    }
 
    var srcImage;
    return this._loadImg(this._srcPath, this._srcOpts).then(image => {
        srcImage = image;
        return this._loadImg(dstPath, dstOpts);
    }).then(dstImage => {
 
        var diffImage, diffData = null;
        Eif (diffPath) {
            diffImage = new PNG({ width: srcImage.width, height: srcImage.height });
            diffData = diffImage.data;
        };
 
        var diffPixels = pixelmatch(
            srcImage.data, dstImage.data, diffData,
            srcImage.width, srcImage.height, { threshold: tolerance });
 
        var diff = _.round(diffPixels / (srcImage.width * srcImage.height), 2);
 
        Eif (diffImage) {
            return new Promise((resolve, reject) => {
                var stream = fs.createWriteStream(diffPath);
                stream.on("finish", () => stream.close(() => resolve(diff)));
                stream.on("error", reject);
                diffImage.pack().pipe(stream);
            });
        } else {
            return diff;
        }
    });
};
/**
 * Loads image.
 *
 * @async
 * @method
 * @protected
 * @arg {string} imgPath - path loaded image
 * @arg {object} imgOpts - image options
 * @return {Promise<object>} - image data
 */
Image.prototype._loadImg = function(imgPath, imgOpts) {
    var width, height, hasAlpha, channels;
    var img = this.__sharp(imgPath);
    return img.metadata().then(metadata => {
        hasAlpha = metadata.hasAlpha;
        channels = metadata.channels;
        width = Math.ceil(metadata.width / imgOpts.scaleX);
        height = Math.ceil(metadata.height / imgOpts.scaleY);
        return img.resize(width, height).raw().toBuffer();
    }).then(data => {
        return { width: width,
            height: height,
            data: data,
            channels: channels,
            hasAlpha: hasAlpha };
    });
};
/**
 * Saves matched part of image.
 *
 * @async
 * @method
 * @protected
 * @arg {number} left - offset from left image border
 * @arg {number} top - offset from top image border
 * @arg {number} width - width of matched part
 * @arg {number} height - height of matched part
 * @return {Promise<void>}
 */
Image.prototype._saveMatchImage = function (left, top, width, height) {
    return this.__sharp(this._srcPath)
        .extract({ left: left, top: top, width: width, height: height })
        .toFile(this._matchedPath);
};
/**
 * Defines whether one image data includes another.
 *
 * @method
 * @protected
 * @arg {object} src - source image data
 * @arg {object} dst - destination image data, which is potentially included
 * @return {object} - result
 */
Image.prototype._includes = function (src, dst) {
 
    var srcPixels = this._cropPixels(this._getPixels(src)),
        dstPixels = this._cropPixels(this._getPixels(dst));
    var offsetX, offsetY, diffValue;
 
    var srcWidth = srcPixels[0].length,
        srcHeight = srcPixels.length,
        dstWidth = dstPixels[0].length,
        dstHeight = dstPixels.length;
 
    var result = { isIncluded: false,
        diffValue:  null,
        offsetX:    null,
        offsetY:    null,
        width:      dstWidth,
        height:     dstHeight };
 
    var deltaX = srcWidth - dstWidth,
        deltaY = srcHeight - dstHeight;
 
    var dstUsedPixels = this._getUsedPixels(dstPixels);
 
    for (offsetY = 0; offsetY <= deltaY; offsetY++) {
        for (offsetX = 0; offsetX <= deltaX; offsetX++) {
 
            diffValue = this._getDiffValue(srcPixels, dstUsedPixels,
                offsetX, offsetY);
            if (diffValue === null) continue;
 
            Eif (result.diffValue === null || result.diffValue > diffValue) {
                result.isIncluded = true;
                result.diffValue = diffValue;
                result.offsetX = offsetX;
                result.offsetY = offsetY;
            };
 
            Eif (diffValue === 0 || !this._saveMatch) return result;
        };
    };
    return result;
};
/**
 * Gets used pixels.
 *
 * @method
 * @protected
 * @arg {object[][]} pixels - pixels matrix
 * @return {object[]} List of used pixels.
 */
Image.prototype._getUsedPixels = function (pixels) {
 
    var usedPixels = [],
        width = pixels[0].length,
        height = pixels.length,
        x, y,
        row;
 
    for (y = 0; y < height; y++) {
        row = pixels[y];
 
        for (x = 0; x < width; x++) {
            if (this._isPixelUsed(row[x])) {
                usedPixels.push({ pixel: row[x], x: x, y: y });
            };
        };
    };
 
    return usedPixels;
};
/**
 * Calculates difference between source pixels and destination pixels.
 *
 * @method
 * @protected
 * @arg {object[][]} srcPixels - source pixels matrix
 * @arg {object[][]} dstPixels - destination pixels matrix
 * @arg {number} offsetX - source left border offset
 * @arg {number} offsetY - source top border offset
 * @return {number} - difference value
 */
Image.prototype._getDiffValue = function (srcPixels, dstPixels,
    offsetX, offsetY) {
    var diffPixels = 0,
        limit = this._tolerance * dstPixels.length,
        dstPixel,
        srcPixel,
        i;
 
    for (i = 0; i < dstPixels.length; i++) {
        dstPixel = dstPixels[i];
        srcPixel = srcPixels[offsetY + dstPixel.y][offsetX + dstPixel.x];
 
        if (this._isPixelTolerant(srcPixel, dstPixel.pixel))
            continue;
 
        diffPixels++;
        if (diffPixels > limit) return null;
    };
    return diffPixels / dstPixels.length;
};
/**
 * Defines whether pixel should be used for difference calculation or no,
 *  according its alpha value.
 *
 * @method
 * @protected
 * @arg {object} pixel - pixel
 * @return {boolean} - `true` if should be, `false` otherwise
 */
Image.prototype._isPixelUsed = function (pixel) {
    return (255 - pixel.A) / 255 < this._tolerance;
};
/**
 * Defines whether source pixel is tolerant to destination pixel.
 *
 * @method
 * @protected
 * @arg {object} srcPixel - source pixel
 * @arg {object} dstPixel - destination pixel
 * @return {boolean} - `true` if pixels are tolerant, `false` otherwise
 */
Image.prototype._isPixelTolerant = function(srcPixel, dstPixel) {
    var deltaR = srcPixel.R - dstPixel.R,
        deltaG = srcPixel.G - dstPixel.G,
        deltaB = srcPixel.B - dstPixel.B;
 
    return Math.sqrt(deltaR * deltaR +
                     deltaG * deltaG +
                     deltaB * deltaB) /
        this._pixelDenominator < this._tolerance;
};
/**
 * Retrieves pixels from image data.
 *
 * @method
 * @protected
 * @arg {object} img - image data
 * @return {object[][]} - pixels matrix
 */
Image.prototype._getPixels = function (img) {
    var pixels = [],
        height = img.height,
        width = img.width * img.channels,
        x, y, offset;
 
    for (y = 0; y < height; y++) {
        offset = width * y;
        pixels.push([]);
 
        for (x = 0; x < width; x += img.channels) {
            pixels[y].push({
                R: img.data[offset + x],
                G: img.data[offset + x + 1],
                B: img.data[offset + x + 2],
                A: img.hasAlpha ? img.data[offset + x + 3] : 255,
            });
        };
    };
    return pixels;
};
/**
 * Crops pixels, removes empty rows and columns.
 *
 * @method
 * @protected
 * @arg {object[][]} pixels - pixels matrix
 * @return {object[][]} - cropped pixels matrix
 */
Image.prototype._cropPixels = function (pixels) {
 
    pixels = this._cropTop(pixels);
    pixels.reverse();
    pixels = this._cropTop(pixels);
    pixels.reverse();
    pixels = this._transpose(pixels);
    pixels = this._cropTop(pixels);
    pixels.reverse();
    pixels = this._cropTop(pixels);
    pixels.reverse();
    return this._transpose(pixels);
};
/**
 * Crops top part of pixels matrix.
 *
 * @method
 * @protected
 * @arg {object[][]} pixels - pixels matrix
 * @return {object[][]} - cropped pixels matrix
 */
Image.prototype._cropTop = function (pixels) {
 
    var croppedPixels = [],
        isTransparent = true,
        width = pixels[0].length,
        height = pixels.length,
        x, y, pixelsRow;
 
    for (y = 0; y < height; y++) {
        pixelsRow = pixels[y];
 
        if (isTransparent) {
            for (x = 0; x < width; x++) {
                if (pixelsRow[x].A !== 0) {
                    isTransparent = false;
                    break;
                };
            };
        };
 
        if (!isTransparent)
            croppedPixels.push(pixelsRow);
    };
    return croppedPixels;
};
/**
 * Transposes pixels matrix.
 *
 * @method
 * @arg {object[][]} pixels - pixels matrix
 * @return {object[][]} transposed pixels matrix
 */
Image.prototype._transpose = function (pixels) {
 
    var width = pixels[0].length,
        height = pixels.length,
        tPixels = [],
        x, y;
 
    Iif (width === 0 || height === 0)
        return [];
 
    for (y = 0; y < width; y++) {
        tPixels[y] = [];
 
        for (x = 0; x < height; x++) {
            tPixels[y][x] = pixels[x][y];
        };
    };
    return tPixels;
};
 
module.exports = Image;