All files / pdf.js/build/lib/core image.js

27.2% Statements 105/386
27.11% Branches 61/225
50% Functions 9/18
28.1% Lines 102/363
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   1x   1x     1x                                                             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x           1x         1x 1x 1x     1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x                               1x 1x   1x 1x 1x                       1x             1x                                       1x 1x 1x 1x 1x 1x 1x 1x   1x     1x 1x 1x       1x 1x                   1x     1x 1x 1x 1x 1x   1x                   1x                                                                   1x   1x     1x                                                                                                                                                                                                                                                                                                                                                   1x   1x 1x 1x       1x 1x 1x 1x 1x   1x   1x   1x 1x   1x 1x 1x 1x 1x           1x             1x                                                                                                                                       1x   1x 1x 1x 1x 1x     1x   1x
/* Copyright 2017 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PDFImage = undefined;
 
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { Eif (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
 
var _util = require('../shared/util');
 
var _primitives = require('./primitives');
 
var _colorspace = require('./colorspace');
 
var _stream = require('./stream');
 
var _jpeg_stream = require('./jpeg_stream');
 
var _jpx = require('./jpx');
 
var PDFImage = function PDFImageClosure() {
  function handleImageData(image, nativeDecoder) {
    Iif (nativeDecoder && nativeDecoder.canDecode(image)) {
      return nativeDecoder.decode(image);
    }
    return Promise.resolve(image);
  }
  function decodeAndClamp(value, addend, coefficient, max) {
    value = addend + value * coefficient;
    return value < 0 ? 0 : value > max ? max : value;
  }
  function resizeImageMask(src, bpc, w1, h1, w2, h2) {
    var length = w2 * h2;
    var dest = bpc <= 8 ? new Uint8Array(length) : bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length);
    var xRatio = w1 / w2;
    var yRatio = h1 / h2;
    var i,
        j,
        py,
        newIndex = 0,
        oldIndex;
    var xScaled = new Uint16Array(w2);
    var w1Scanline = w1;
    for (i = 0; i < w2; i++) {
      xScaled[i] = Math.floor(i * xRatio);
    }
    for (i = 0; i < h2; i++) {
      py = Math.floor(i * yRatio) * w1Scanline;
      for (j = 0; j < w2; j++) {
        oldIndex = py + xScaled[j];
        dest[newIndex++] = src[oldIndex];
      }
    }
    return dest;
  }
  function PDFImage(_ref) {
    var xref = _ref.xref,
        res = _ref.res,
        image = _ref.image,
        _ref$smask = _ref.smask,
        smask = _ref$smask === undefined ? null : _ref$smask,
        _ref$mask = _ref.mask,
        mask = _ref$mask === undefined ? null : _ref$mask,
        _ref$isMask = _ref.isMask,
        isMask = _ref$isMask === undefined ? false : _ref$isMask,
        pdfFunctionFactory = _ref.pdfFunctionFactory;
 
    this.image = image;
    var dict = image.dict;
    Eif (dict.has('Filter')) {
      var filter = dict.get('Filter').name;
      Iif (filter === 'JPXDecode') {
        var jpxImage = new _jpx.JpxImage();
        jpxImage.parseImageProperties(image.stream);
        image.stream.reset();
        image.bitsPerComponent = jpxImage.bitsPerComponent;
        image.numComps = jpxImage.componentsCount;
      } else Iif (filter === 'JBIG2Decode') {
        image.bitsPerComponent = 1;
        image.numComps = 1;
      }
    }
    this.width = dict.get('Width', 'W');
    this.height = dict.get('Height', 'H');
    Iif (this.width < 1 || this.height < 1) {
      throw new _util.FormatError('Invalid image width: ' + this.width + ' or ' + ('height: ' + this.height));
    }
    this.interpolate = dict.get('Interpolate', 'I') || false;
    this.imageMask = dict.get('ImageMask', 'IM') || false;
    this.matte = dict.get('Matte') || false;
    var bitsPerComponent = image.bitsPerComponent;
    Eif (!bitsPerComponent) {
      bitsPerComponent = dict.get('BitsPerComponent', 'BPC');
      Iif (!bitsPerComponent) {
        if (this.imageMask) {
          bitsPerComponent = 1;
        } else {
          throw new _util.FormatError('Bits per component missing in image: ' + this.imageMask);
        }
      }
    }
    this.bpc = bitsPerComponent;
    Eif (!this.imageMask) {
      var colorSpace = dict.get('ColorSpace', 'CS');
      Iif (!colorSpace) {
        (0, _util.info)('JPX images (which do not require color spaces)');
        switch (image.numComps) {
          case 1:
            colorSpace = _primitives.Name.get('DeviceGray');
            break;
          case 3:
            colorSpace = _primitives.Name.get('DeviceRGB');
            break;
          case 4:
            colorSpace = _primitives.Name.get('DeviceCMYK');
            break;
          default:
            throw new Error('JPX images with ' + this.numComps + ' ' + 'color components not supported.');
        }
      }
      this.colorSpace = _colorspace.ColorSpace.parse(colorSpace, xref, res, pdfFunctionFactory);
      this.numComps = this.colorSpace.numComps;
    }
    this.decode = dict.getArray('Decode', 'D');
    this.needsDecode = false;
    Iif (this.decode && (this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode) || isMask && !_colorspace.ColorSpace.isDefaultDecode(this.decode, 1))) {
      this.needsDecode = true;
      var max = (1 << bitsPerComponent) - 1;
      this.decodeCoefficients = [];
      this.decodeAddends = [];
      for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
        var dmin = this.decode[i];
        var dmax = this.decode[i + 1];
        this.decodeCoefficients[j] = dmax - dmin;
        this.decodeAddends[j] = max * dmin;
      }
    }
    Iif (smask) {
      this.smask = new PDFImage({
        xref: xref,
        res: res,
        image: smask,
        pdfFunctionFactory: pdfFunctionFactory
      });
    } else Iif (mask) {
      if ((0, _primitives.isStream)(mask)) {
        var maskDict = mask.dict,
            imageMask = maskDict.get('ImageMask', 'IM');
        if (!imageMask) {
          (0, _util.warn)('Ignoring /Mask in image without /ImageMask.');
        } else {
          this.mask = new PDFImage({
            xref: xref,
            res: res,
            image: mask,
            isMask: true,
            pdfFunctionFactory: pdfFunctionFactory
          });
        }
      } else {
        this.mask = mask;
      }
    }
  }
  PDFImage.buildImage = function (_ref2) {
    var handler = _ref2.handler,
        xref = _ref2.xref,
        res = _ref2.res,
        image = _ref2.image,
        _ref2$nativeDecoder = _ref2.nativeDecoder,
        nativeDecoder = _ref2$nativeDecoder === undefined ? null : _ref2$nativeDecoder,
        pdfFunctionFactory = _ref2.pdfFunctionFactory;
 
    var imagePromise = handleImageData(image, nativeDecoder);
    var smaskPromise;
    var maskPromise;
    var smask = image.dict.get('SMask');
    var mask = image.dict.get('Mask');
    Iif (smask) {
      smaskPromise = handleImageData(smask, nativeDecoder);
      maskPromise = Promise.resolve(null);
    } else {
      smaskPromise = Promise.resolve(null);
      Iif (mask) {
        if ((0, _primitives.isStream)(mask)) {
          maskPromise = handleImageData(mask, nativeDecoder);
        } else if (Array.isArray(mask)) {
          maskPromise = Promise.resolve(mask);
        } else {
          (0, _util.warn)('Unsupported mask format.');
          maskPromise = Promise.resolve(null);
        }
      } else {
        maskPromise = Promise.resolve(null);
      }
    }
    return Promise.all([imagePromise, smaskPromise, maskPromise]).then(function (_ref3) {
      var _ref4 = _slicedToArray(_ref3, 3),
          imageData = _ref4[0],
          smaskData = _ref4[1],
          maskData = _ref4[2];
 
      return new PDFImage({
        xref: xref,
        res: res,
        image: imageData,
        smask: smaskData,
        mask: maskData,
        pdfFunctionFactory: pdfFunctionFactory
      });
    });
  };
  PDFImage.createMask = function (_ref5) {
    var imgArray = _ref5.imgArray,
        width = _ref5.width,
        height = _ref5.height,
        imageIsFromDecodeStream = _ref5.imageIsFromDecodeStream,
        inverseDecode = _ref5.inverseDecode;
 
    var computedLength = (width + 7 >> 3) * height;
    var actualLength = imgArray.byteLength;
    var haveFullData = computedLength === actualLength;
    var data, i;
    if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
      data = imgArray;
    } else if (!inverseDecode) {
      data = new Uint8Array(actualLength);
      data.set(imgArray);
    } else {
      data = new Uint8Array(computedLength);
      data.set(imgArray);
      for (i = actualLength; i < computedLength; i++) {
        data[i] = 0xff;
      }
    }
    if (inverseDecode) {
      for (i = 0; i < actualLength; i++) {
        data[i] ^= 0xFF;
      }
    }
    return {
      data: data,
      width: width,
      height: height
    };
  };
  PDFImage.prototype = {
    get drawWidth() {
      return Math.max(this.width, this.smask && this.smask.width || 0, this.mask && this.mask.width || 0);
    },
    get drawHeight() {
      return Math.max(this.height, this.smask && this.smask.height || 0, this.mask && this.mask.height || 0);
    },
    decodeBuffer: function decodeBuffer(buffer) {
      var bpc = this.bpc;
      var numComps = this.numComps;
      var decodeAddends = this.decodeAddends;
      var decodeCoefficients = this.decodeCoefficients;
      var max = (1 << bpc) - 1;
      var i, ii;
      if (bpc === 1) {
        for (i = 0, ii = buffer.length; i < ii; i++) {
          buffer[i] = +!buffer[i];
        }
        return;
      }
      var index = 0;
      for (i = 0, ii = this.width * this.height; i < ii; i++) {
        for (var j = 0; j < numComps; j++) {
          buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j], decodeCoefficients[j], max);
          index++;
        }
      }
    },
    getComponents: function getComponents(buffer) {
      var bpc = this.bpc;
      if (bpc === 8) {
        return buffer;
      }
      var width = this.width;
      var height = this.height;
      var numComps = this.numComps;
      var length = width * height * numComps;
      var bufferPos = 0;
      var output = bpc <= 8 ? new Uint8Array(length) : bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length);
      var rowComps = width * numComps;
      var max = (1 << bpc) - 1;
      var i = 0,
          ii,
          buf;
      if (bpc === 1) {
        var mask, loop1End, loop2End;
        for (var j = 0; j < height; j++) {
          loop1End = i + (rowComps & ~7);
          loop2End = i + rowComps;
          while (i < loop1End) {
            buf = buffer[bufferPos++];
            output[i] = buf >> 7 & 1;
            output[i + 1] = buf >> 6 & 1;
            output[i + 2] = buf >> 5 & 1;
            output[i + 3] = buf >> 4 & 1;
            output[i + 4] = buf >> 3 & 1;
            output[i + 5] = buf >> 2 & 1;
            output[i + 6] = buf >> 1 & 1;
            output[i + 7] = buf & 1;
            i += 8;
          }
          if (i < loop2End) {
            buf = buffer[bufferPos++];
            mask = 128;
            while (i < loop2End) {
              output[i++] = +!!(buf & mask);
              mask >>= 1;
            }
          }
        }
      } else {
        var bits = 0;
        buf = 0;
        for (i = 0, ii = length; i < ii; ++i) {
          if (i % rowComps === 0) {
            buf = 0;
            bits = 0;
          }
          while (bits < bpc) {
            buf = buf << 8 | buffer[bufferPos++];
            bits += 8;
          }
          var remainingBits = bits - bpc;
          var value = buf >> remainingBits;
          output[i] = value < 0 ? 0 : value > max ? max : value;
          buf = buf & (1 << remainingBits) - 1;
          bits = remainingBits;
        }
      }
      return output;
    },
    fillOpacity: function fillOpacity(rgbaBuf, width, height, actualHeight, image) {
      var smask = this.smask;
      var mask = this.mask;
      var alphaBuf, sw, sh, i, ii, j;
      if (smask) {
        sw = smask.width;
        sh = smask.height;
        alphaBuf = new Uint8Array(sw * sh);
        smask.fillGrayBuffer(alphaBuf);
        if (sw !== width || sh !== height) {
          alphaBuf = resizeImageMask(alphaBuf, smask.bpc, sw, sh, width, height);
        }
      } else if (mask) {
        if (mask instanceof PDFImage) {
          sw = mask.width;
          sh = mask.height;
          alphaBuf = new Uint8Array(sw * sh);
          mask.numComps = 1;
          mask.fillGrayBuffer(alphaBuf);
          for (i = 0, ii = sw * sh; i < ii; ++i) {
            alphaBuf[i] = 255 - alphaBuf[i];
          }
          if (sw !== width || sh !== height) {
            alphaBuf = resizeImageMask(alphaBuf, mask.bpc, sw, sh, width, height);
          }
        } else if (Array.isArray(mask)) {
          alphaBuf = new Uint8Array(width * height);
          var numComps = this.numComps;
          for (i = 0, ii = width * height; i < ii; ++i) {
            var opacity = 0;
            var imageOffset = i * numComps;
            for (j = 0; j < numComps; ++j) {
              var color = image[imageOffset + j];
              var maskOffset = j * 2;
              if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
                opacity = 255;
                break;
              }
            }
            alphaBuf[i] = opacity;
          }
        } else {
          throw new _util.FormatError('Unknown mask format.');
        }
      }
      if (alphaBuf) {
        for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
          rgbaBuf[j] = alphaBuf[i];
        }
      } else {
        for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
          rgbaBuf[j] = 255;
        }
      }
    },
    undoPreblend: function undoPreblend(buffer, width, height) {
      var matte = this.smask && this.smask.matte;
      if (!matte) {
        return;
      }
      var matteRgb = this.colorSpace.getRgb(matte, 0);
      var matteR = matteRgb[0];
      var matteG = matteRgb[1];
      var matteB = matteRgb[2];
      var length = width * height * 4;
      var r, g, b;
      for (var i = 0; i < length; i += 4) {
        var alpha = buffer[i + 3];
        if (alpha === 0) {
          buffer[i] = 255;
          buffer[i + 1] = 255;
          buffer[i + 2] = 255;
          continue;
        }
        var k = 255 / alpha;
        r = (buffer[i] - matteR) * k + matteR;
        g = (buffer[i + 1] - matteG) * k + matteG;
        b = (buffer[i + 2] - matteB) * k + matteB;
        buffer[i] = r <= 0 ? 0 : r >= 255 ? 255 : r | 0;
        buffer[i + 1] = g <= 0 ? 0 : g >= 255 ? 255 : g | 0;
        buffer[i + 2] = b <= 0 ? 0 : b >= 255 ? 255 : b | 0;
      }
    },
    createImageData: function createImageData() {
      var forceRGBA = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
 
      var drawWidth = this.drawWidth;
      var drawHeight = this.drawHeight;
      var imgData = {
        width: drawWidth,
        height: drawHeight
      };
      var numComps = this.numComps;
      var originalWidth = this.width;
      var originalHeight = this.height;
      var bpc = this.bpc;
      var rowBytes = originalWidth * numComps * bpc + 7 >> 3;
      var imgArray;
      Eif (!forceRGBA) {
        var kind;
        Iif (this.colorSpace.name === 'DeviceGray' && bpc === 1) {
          kind = _util.ImageKind.GRAYSCALE_1BPP;
        } else Eif (this.colorSpace.name === 'DeviceRGB' && bpc === 8 && !this.needsDecode) {
          kind = _util.ImageKind.RGB_24BPP;
        }
        Eif (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) {
          imgData.kind = kind;
          imgArray = this.getImageBytes(originalHeight * rowBytes);
          Eif (this.image instanceof _stream.DecodeStream) {
            imgData.data = imgArray;
          } else {
            var newArray = new Uint8Array(imgArray.length);
            newArray.set(imgArray);
            imgData.data = newArray;
          }
          Iif (this.needsDecode) {
            (0, _util.assert)(kind === _util.ImageKind.GRAYSCALE_1BPP);
            var buffer = imgData.data;
            for (var i = 0, ii = buffer.length; i < ii; i++) {
              buffer[i] ^= 0xff;
            }
          }
          return imgData;
        }
        if (this.image instanceof _jpeg_stream.JpegStream && !this.smask && !this.mask && (this.colorSpace.name === 'DeviceGray' || this.colorSpace.name === 'DeviceRGB' || this.colorSpace.name === 'DeviceCMYK')) {
          imgData.kind = _util.ImageKind.RGB_24BPP;
          imgData.data = this.getImageBytes(originalHeight * rowBytes, drawWidth, drawHeight, true);
          return imgData;
        }
      }
      imgArray = this.getImageBytes(originalHeight * rowBytes);
      var actualHeight = 0 | imgArray.length / rowBytes * drawHeight / originalHeight;
      var comps = this.getComponents(imgArray);
      var alpha01, maybeUndoPreblend;
      if (!forceRGBA && !this.smask && !this.mask) {
        imgData.kind = _util.ImageKind.RGB_24BPP;
        imgData.data = new Uint8Array(drawWidth * drawHeight * 3);
        alpha01 = 0;
        maybeUndoPreblend = false;
      } else {
        imgData.kind = _util.ImageKind.RGBA_32BPP;
        imgData.data = new Uint8Array(drawWidth * drawHeight * 4);
        alpha01 = 1;
        maybeUndoPreblend = true;
        this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight, comps);
      }
      if (this.needsDecode) {
        this.decodeBuffer(comps);
      }
      this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight, drawWidth, drawHeight, actualHeight, bpc, comps, alpha01);
      if (maybeUndoPreblend) {
        this.undoPreblend(imgData.data, drawWidth, actualHeight);
      }
      return imgData;
    },
    fillGrayBuffer: function fillGrayBuffer(buffer) {
      var numComps = this.numComps;
      if (numComps !== 1) {
        throw new _util.FormatError('Reading gray scale from a color image: ' + numComps);
      }
      var width = this.width;
      var height = this.height;
      var bpc = this.bpc;
      var rowBytes = width * numComps * bpc + 7 >> 3;
      var imgArray = this.getImageBytes(height * rowBytes);
      var comps = this.getComponents(imgArray);
      var i, length;
      if (bpc === 1) {
        length = width * height;
        if (this.needsDecode) {
          for (i = 0; i < length; ++i) {
            buffer[i] = comps[i] - 1 & 255;
          }
        } else {
          for (i = 0; i < length; ++i) {
            buffer[i] = -comps[i] & 255;
          }
        }
        return;
      }
      if (this.needsDecode) {
        this.decodeBuffer(comps);
      }
      length = width * height;
      var scale = 255 / ((1 << bpc) - 1);
      for (i = 0; i < length; ++i) {
        buffer[i] = scale * comps[i] | 0;
      }
    },
    getImageBytes: function getImageBytes(length, drawWidth, drawHeight) {
      var forceRGB = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
 
      this.image.reset();
      this.image.drawWidth = drawWidth || this.width;
      this.image.drawHeight = drawHeight || this.height;
      this.image.forceRGB = !!forceRGB;
      return this.image.getBytes(length);
    }
  };
  return PDFImage;
}();
exports.PDFImage = PDFImage;