2
0

image.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2017 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. 'use strict';
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PDFImage = undefined;
  27. 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) { if (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"); } }; }();
  28. var _util = require('../shared/util');
  29. var _primitives = require('./primitives');
  30. var _colorspace = require('./colorspace');
  31. var _stream = require('./stream');
  32. var _jpeg_stream = require('./jpeg_stream');
  33. var _jpx = require('./jpx');
  34. var PDFImage = function PDFImageClosure() {
  35. function handleImageData(image, nativeDecoder) {
  36. if (nativeDecoder && nativeDecoder.canDecode(image)) {
  37. return nativeDecoder.decode(image);
  38. }
  39. return Promise.resolve(image);
  40. }
  41. function decodeAndClamp(value, addend, coefficient, max) {
  42. value = addend + value * coefficient;
  43. return value < 0 ? 0 : value > max ? max : value;
  44. }
  45. function resizeImageMask(src, bpc, w1, h1, w2, h2) {
  46. var length = w2 * h2;
  47. var dest = bpc <= 8 ? new Uint8Array(length) : bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length);
  48. var xRatio = w1 / w2;
  49. var yRatio = h1 / h2;
  50. var i,
  51. j,
  52. py,
  53. newIndex = 0,
  54. oldIndex;
  55. var xScaled = new Uint16Array(w2);
  56. var w1Scanline = w1;
  57. for (i = 0; i < w2; i++) {
  58. xScaled[i] = Math.floor(i * xRatio);
  59. }
  60. for (i = 0; i < h2; i++) {
  61. py = Math.floor(i * yRatio) * w1Scanline;
  62. for (j = 0; j < w2; j++) {
  63. oldIndex = py + xScaled[j];
  64. dest[newIndex++] = src[oldIndex];
  65. }
  66. }
  67. return dest;
  68. }
  69. function PDFImage(_ref) {
  70. var xref = _ref.xref,
  71. res = _ref.res,
  72. image = _ref.image,
  73. _ref$smask = _ref.smask,
  74. smask = _ref$smask === undefined ? null : _ref$smask,
  75. _ref$mask = _ref.mask,
  76. mask = _ref$mask === undefined ? null : _ref$mask,
  77. _ref$isMask = _ref.isMask,
  78. isMask = _ref$isMask === undefined ? false : _ref$isMask,
  79. pdfFunctionFactory = _ref.pdfFunctionFactory;
  80. this.image = image;
  81. var dict = image.dict;
  82. if (dict.has('Filter')) {
  83. var filter = dict.get('Filter').name;
  84. if (filter === 'JPXDecode') {
  85. var jpxImage = new _jpx.JpxImage();
  86. jpxImage.parseImageProperties(image.stream);
  87. image.stream.reset();
  88. image.bitsPerComponent = jpxImage.bitsPerComponent;
  89. image.numComps = jpxImage.componentsCount;
  90. } else if (filter === 'JBIG2Decode') {
  91. image.bitsPerComponent = 1;
  92. image.numComps = 1;
  93. }
  94. }
  95. this.width = dict.get('Width', 'W');
  96. this.height = dict.get('Height', 'H');
  97. if (this.width < 1 || this.height < 1) {
  98. throw new _util.FormatError('Invalid image width: ' + this.width + ' or ' + ('height: ' + this.height));
  99. }
  100. this.interpolate = dict.get('Interpolate', 'I') || false;
  101. this.imageMask = dict.get('ImageMask', 'IM') || false;
  102. this.matte = dict.get('Matte') || false;
  103. var bitsPerComponent = image.bitsPerComponent;
  104. if (!bitsPerComponent) {
  105. bitsPerComponent = dict.get('BitsPerComponent', 'BPC');
  106. if (!bitsPerComponent) {
  107. if (this.imageMask) {
  108. bitsPerComponent = 1;
  109. } else {
  110. throw new _util.FormatError('Bits per component missing in image: ' + this.imageMask);
  111. }
  112. }
  113. }
  114. this.bpc = bitsPerComponent;
  115. if (!this.imageMask) {
  116. var colorSpace = dict.get('ColorSpace', 'CS');
  117. if (!colorSpace) {
  118. (0, _util.info)('JPX images (which do not require color spaces)');
  119. switch (image.numComps) {
  120. case 1:
  121. colorSpace = _primitives.Name.get('DeviceGray');
  122. break;
  123. case 3:
  124. colorSpace = _primitives.Name.get('DeviceRGB');
  125. break;
  126. case 4:
  127. colorSpace = _primitives.Name.get('DeviceCMYK');
  128. break;
  129. default:
  130. throw new Error('JPX images with ' + this.numComps + ' ' + 'color components not supported.');
  131. }
  132. }
  133. this.colorSpace = _colorspace.ColorSpace.parse(colorSpace, xref, res, pdfFunctionFactory);
  134. this.numComps = this.colorSpace.numComps;
  135. }
  136. this.decode = dict.getArray('Decode', 'D');
  137. this.needsDecode = false;
  138. if (this.decode && (this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode) || isMask && !_colorspace.ColorSpace.isDefaultDecode(this.decode, 1))) {
  139. this.needsDecode = true;
  140. var max = (1 << bitsPerComponent) - 1;
  141. this.decodeCoefficients = [];
  142. this.decodeAddends = [];
  143. for (var i = 0, j = 0; i < this.decode.length; i += 2, ++j) {
  144. var dmin = this.decode[i];
  145. var dmax = this.decode[i + 1];
  146. this.decodeCoefficients[j] = dmax - dmin;
  147. this.decodeAddends[j] = max * dmin;
  148. }
  149. }
  150. if (smask) {
  151. this.smask = new PDFImage({
  152. xref: xref,
  153. res: res,
  154. image: smask,
  155. pdfFunctionFactory: pdfFunctionFactory
  156. });
  157. } else if (mask) {
  158. if ((0, _primitives.isStream)(mask)) {
  159. var maskDict = mask.dict,
  160. imageMask = maskDict.get('ImageMask', 'IM');
  161. if (!imageMask) {
  162. (0, _util.warn)('Ignoring /Mask in image without /ImageMask.');
  163. } else {
  164. this.mask = new PDFImage({
  165. xref: xref,
  166. res: res,
  167. image: mask,
  168. isMask: true,
  169. pdfFunctionFactory: pdfFunctionFactory
  170. });
  171. }
  172. } else {
  173. this.mask = mask;
  174. }
  175. }
  176. }
  177. PDFImage.buildImage = function (_ref2) {
  178. var handler = _ref2.handler,
  179. xref = _ref2.xref,
  180. res = _ref2.res,
  181. image = _ref2.image,
  182. _ref2$nativeDecoder = _ref2.nativeDecoder,
  183. nativeDecoder = _ref2$nativeDecoder === undefined ? null : _ref2$nativeDecoder,
  184. pdfFunctionFactory = _ref2.pdfFunctionFactory;
  185. var imagePromise = handleImageData(image, nativeDecoder);
  186. var smaskPromise;
  187. var maskPromise;
  188. var smask = image.dict.get('SMask');
  189. var mask = image.dict.get('Mask');
  190. if (smask) {
  191. smaskPromise = handleImageData(smask, nativeDecoder);
  192. maskPromise = Promise.resolve(null);
  193. } else {
  194. smaskPromise = Promise.resolve(null);
  195. if (mask) {
  196. if ((0, _primitives.isStream)(mask)) {
  197. maskPromise = handleImageData(mask, nativeDecoder);
  198. } else if (Array.isArray(mask)) {
  199. maskPromise = Promise.resolve(mask);
  200. } else {
  201. (0, _util.warn)('Unsupported mask format.');
  202. maskPromise = Promise.resolve(null);
  203. }
  204. } else {
  205. maskPromise = Promise.resolve(null);
  206. }
  207. }
  208. return Promise.all([imagePromise, smaskPromise, maskPromise]).then(function (_ref3) {
  209. var _ref4 = _slicedToArray(_ref3, 3),
  210. imageData = _ref4[0],
  211. smaskData = _ref4[1],
  212. maskData = _ref4[2];
  213. return new PDFImage({
  214. xref: xref,
  215. res: res,
  216. image: imageData,
  217. smask: smaskData,
  218. mask: maskData,
  219. pdfFunctionFactory: pdfFunctionFactory
  220. });
  221. });
  222. };
  223. PDFImage.createMask = function (_ref5) {
  224. var imgArray = _ref5.imgArray,
  225. width = _ref5.width,
  226. height = _ref5.height,
  227. imageIsFromDecodeStream = _ref5.imageIsFromDecodeStream,
  228. inverseDecode = _ref5.inverseDecode;
  229. var computedLength = (width + 7 >> 3) * height;
  230. var actualLength = imgArray.byteLength;
  231. var haveFullData = computedLength === actualLength;
  232. var data, i;
  233. if (imageIsFromDecodeStream && (!inverseDecode || haveFullData)) {
  234. data = imgArray;
  235. } else if (!inverseDecode) {
  236. data = new Uint8Array(actualLength);
  237. data.set(imgArray);
  238. } else {
  239. data = new Uint8Array(computedLength);
  240. data.set(imgArray);
  241. for (i = actualLength; i < computedLength; i++) {
  242. data[i] = 0xff;
  243. }
  244. }
  245. if (inverseDecode) {
  246. for (i = 0; i < actualLength; i++) {
  247. data[i] ^= 0xFF;
  248. }
  249. }
  250. return {
  251. data: data,
  252. width: width,
  253. height: height
  254. };
  255. };
  256. PDFImage.prototype = {
  257. get drawWidth() {
  258. return Math.max(this.width, this.smask && this.smask.width || 0, this.mask && this.mask.width || 0);
  259. },
  260. get drawHeight() {
  261. return Math.max(this.height, this.smask && this.smask.height || 0, this.mask && this.mask.height || 0);
  262. },
  263. decodeBuffer: function decodeBuffer(buffer) {
  264. var bpc = this.bpc;
  265. var numComps = this.numComps;
  266. var decodeAddends = this.decodeAddends;
  267. var decodeCoefficients = this.decodeCoefficients;
  268. var max = (1 << bpc) - 1;
  269. var i, ii;
  270. if (bpc === 1) {
  271. for (i = 0, ii = buffer.length; i < ii; i++) {
  272. buffer[i] = +!buffer[i];
  273. }
  274. return;
  275. }
  276. var index = 0;
  277. for (i = 0, ii = this.width * this.height; i < ii; i++) {
  278. for (var j = 0; j < numComps; j++) {
  279. buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j], decodeCoefficients[j], max);
  280. index++;
  281. }
  282. }
  283. },
  284. getComponents: function getComponents(buffer) {
  285. var bpc = this.bpc;
  286. if (bpc === 8) {
  287. return buffer;
  288. }
  289. var width = this.width;
  290. var height = this.height;
  291. var numComps = this.numComps;
  292. var length = width * height * numComps;
  293. var bufferPos = 0;
  294. var output = bpc <= 8 ? new Uint8Array(length) : bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length);
  295. var rowComps = width * numComps;
  296. var max = (1 << bpc) - 1;
  297. var i = 0,
  298. ii,
  299. buf;
  300. if (bpc === 1) {
  301. var mask, loop1End, loop2End;
  302. for (var j = 0; j < height; j++) {
  303. loop1End = i + (rowComps & ~7);
  304. loop2End = i + rowComps;
  305. while (i < loop1End) {
  306. buf = buffer[bufferPos++];
  307. output[i] = buf >> 7 & 1;
  308. output[i + 1] = buf >> 6 & 1;
  309. output[i + 2] = buf >> 5 & 1;
  310. output[i + 3] = buf >> 4 & 1;
  311. output[i + 4] = buf >> 3 & 1;
  312. output[i + 5] = buf >> 2 & 1;
  313. output[i + 6] = buf >> 1 & 1;
  314. output[i + 7] = buf & 1;
  315. i += 8;
  316. }
  317. if (i < loop2End) {
  318. buf = buffer[bufferPos++];
  319. mask = 128;
  320. while (i < loop2End) {
  321. output[i++] = +!!(buf & mask);
  322. mask >>= 1;
  323. }
  324. }
  325. }
  326. } else {
  327. var bits = 0;
  328. buf = 0;
  329. for (i = 0, ii = length; i < ii; ++i) {
  330. if (i % rowComps === 0) {
  331. buf = 0;
  332. bits = 0;
  333. }
  334. while (bits < bpc) {
  335. buf = buf << 8 | buffer[bufferPos++];
  336. bits += 8;
  337. }
  338. var remainingBits = bits - bpc;
  339. var value = buf >> remainingBits;
  340. output[i] = value < 0 ? 0 : value > max ? max : value;
  341. buf = buf & (1 << remainingBits) - 1;
  342. bits = remainingBits;
  343. }
  344. }
  345. return output;
  346. },
  347. fillOpacity: function fillOpacity(rgbaBuf, width, height, actualHeight, image) {
  348. var smask = this.smask;
  349. var mask = this.mask;
  350. var alphaBuf, sw, sh, i, ii, j;
  351. if (smask) {
  352. sw = smask.width;
  353. sh = smask.height;
  354. alphaBuf = new Uint8Array(sw * sh);
  355. smask.fillGrayBuffer(alphaBuf);
  356. if (sw !== width || sh !== height) {
  357. alphaBuf = resizeImageMask(alphaBuf, smask.bpc, sw, sh, width, height);
  358. }
  359. } else if (mask) {
  360. if (mask instanceof PDFImage) {
  361. sw = mask.width;
  362. sh = mask.height;
  363. alphaBuf = new Uint8Array(sw * sh);
  364. mask.numComps = 1;
  365. mask.fillGrayBuffer(alphaBuf);
  366. for (i = 0, ii = sw * sh; i < ii; ++i) {
  367. alphaBuf[i] = 255 - alphaBuf[i];
  368. }
  369. if (sw !== width || sh !== height) {
  370. alphaBuf = resizeImageMask(alphaBuf, mask.bpc, sw, sh, width, height);
  371. }
  372. } else if (Array.isArray(mask)) {
  373. alphaBuf = new Uint8Array(width * height);
  374. var numComps = this.numComps;
  375. for (i = 0, ii = width * height; i < ii; ++i) {
  376. var opacity = 0;
  377. var imageOffset = i * numComps;
  378. for (j = 0; j < numComps; ++j) {
  379. var color = image[imageOffset + j];
  380. var maskOffset = j * 2;
  381. if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
  382. opacity = 255;
  383. break;
  384. }
  385. }
  386. alphaBuf[i] = opacity;
  387. }
  388. } else {
  389. throw new _util.FormatError('Unknown mask format.');
  390. }
  391. }
  392. if (alphaBuf) {
  393. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  394. rgbaBuf[j] = alphaBuf[i];
  395. }
  396. } else {
  397. for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
  398. rgbaBuf[j] = 255;
  399. }
  400. }
  401. },
  402. undoPreblend: function undoPreblend(buffer, width, height) {
  403. var matte = this.smask && this.smask.matte;
  404. if (!matte) {
  405. return;
  406. }
  407. var matteRgb = this.colorSpace.getRgb(matte, 0);
  408. var matteR = matteRgb[0];
  409. var matteG = matteRgb[1];
  410. var matteB = matteRgb[2];
  411. var length = width * height * 4;
  412. var r, g, b;
  413. for (var i = 0; i < length; i += 4) {
  414. var alpha = buffer[i + 3];
  415. if (alpha === 0) {
  416. buffer[i] = 255;
  417. buffer[i + 1] = 255;
  418. buffer[i + 2] = 255;
  419. continue;
  420. }
  421. var k = 255 / alpha;
  422. r = (buffer[i] - matteR) * k + matteR;
  423. g = (buffer[i + 1] - matteG) * k + matteG;
  424. b = (buffer[i + 2] - matteB) * k + matteB;
  425. buffer[i] = r <= 0 ? 0 : r >= 255 ? 255 : r | 0;
  426. buffer[i + 1] = g <= 0 ? 0 : g >= 255 ? 255 : g | 0;
  427. buffer[i + 2] = b <= 0 ? 0 : b >= 255 ? 255 : b | 0;
  428. }
  429. },
  430. createImageData: function createImageData() {
  431. var forceRGBA = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  432. var drawWidth = this.drawWidth;
  433. var drawHeight = this.drawHeight;
  434. var imgData = {
  435. width: drawWidth,
  436. height: drawHeight
  437. };
  438. var numComps = this.numComps;
  439. var originalWidth = this.width;
  440. var originalHeight = this.height;
  441. var bpc = this.bpc;
  442. var rowBytes = originalWidth * numComps * bpc + 7 >> 3;
  443. var imgArray;
  444. if (!forceRGBA) {
  445. var kind;
  446. if (this.colorSpace.name === 'DeviceGray' && bpc === 1) {
  447. kind = _util.ImageKind.GRAYSCALE_1BPP;
  448. } else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8 && !this.needsDecode) {
  449. kind = _util.ImageKind.RGB_24BPP;
  450. }
  451. if (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) {
  452. imgData.kind = kind;
  453. imgArray = this.getImageBytes(originalHeight * rowBytes);
  454. if (this.image instanceof _stream.DecodeStream) {
  455. imgData.data = imgArray;
  456. } else {
  457. var newArray = new Uint8Array(imgArray.length);
  458. newArray.set(imgArray);
  459. imgData.data = newArray;
  460. }
  461. if (this.needsDecode) {
  462. (0, _util.assert)(kind === _util.ImageKind.GRAYSCALE_1BPP);
  463. var buffer = imgData.data;
  464. for (var i = 0, ii = buffer.length; i < ii; i++) {
  465. buffer[i] ^= 0xff;
  466. }
  467. }
  468. return imgData;
  469. }
  470. if (this.image instanceof _jpeg_stream.JpegStream && !this.smask && !this.mask) {
  471. var imageLength = originalHeight * rowBytes;
  472. switch (this.colorSpace.name) {
  473. case 'DeviceGray':
  474. imageLength *= 3;
  475. case 'DeviceRGB':
  476. case 'DeviceCMYK':
  477. imgData.kind = _util.ImageKind.RGB_24BPP;
  478. imgData.data = this.getImageBytes(imageLength, drawWidth, drawHeight, true);
  479. return imgData;
  480. }
  481. }
  482. }
  483. imgArray = this.getImageBytes(originalHeight * rowBytes);
  484. var actualHeight = 0 | imgArray.length / rowBytes * drawHeight / originalHeight;
  485. var comps = this.getComponents(imgArray);
  486. var alpha01, maybeUndoPreblend;
  487. if (!forceRGBA && !this.smask && !this.mask) {
  488. imgData.kind = _util.ImageKind.RGB_24BPP;
  489. imgData.data = new Uint8Array(drawWidth * drawHeight * 3);
  490. alpha01 = 0;
  491. maybeUndoPreblend = false;
  492. } else {
  493. imgData.kind = _util.ImageKind.RGBA_32BPP;
  494. imgData.data = new Uint8Array(drawWidth * drawHeight * 4);
  495. alpha01 = 1;
  496. maybeUndoPreblend = true;
  497. this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight, comps);
  498. }
  499. if (this.needsDecode) {
  500. this.decodeBuffer(comps);
  501. }
  502. this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight, drawWidth, drawHeight, actualHeight, bpc, comps, alpha01);
  503. if (maybeUndoPreblend) {
  504. this.undoPreblend(imgData.data, drawWidth, actualHeight);
  505. }
  506. return imgData;
  507. },
  508. fillGrayBuffer: function fillGrayBuffer(buffer) {
  509. var numComps = this.numComps;
  510. if (numComps !== 1) {
  511. throw new _util.FormatError('Reading gray scale from a color image: ' + numComps);
  512. }
  513. var width = this.width;
  514. var height = this.height;
  515. var bpc = this.bpc;
  516. var rowBytes = width * numComps * bpc + 7 >> 3;
  517. var imgArray = this.getImageBytes(height * rowBytes);
  518. var comps = this.getComponents(imgArray);
  519. var i, length;
  520. if (bpc === 1) {
  521. length = width * height;
  522. if (this.needsDecode) {
  523. for (i = 0; i < length; ++i) {
  524. buffer[i] = comps[i] - 1 & 255;
  525. }
  526. } else {
  527. for (i = 0; i < length; ++i) {
  528. buffer[i] = -comps[i] & 255;
  529. }
  530. }
  531. return;
  532. }
  533. if (this.needsDecode) {
  534. this.decodeBuffer(comps);
  535. }
  536. length = width * height;
  537. var scale = 255 / ((1 << bpc) - 1);
  538. for (i = 0; i < length; ++i) {
  539. buffer[i] = scale * comps[i] | 0;
  540. }
  541. },
  542. getImageBytes: function getImageBytes(length, drawWidth, drawHeight) {
  543. var forceRGB = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  544. this.image.reset();
  545. this.image.drawWidth = drawWidth || this.width;
  546. this.image.drawHeight = drawHeight || this.height;
  547. this.image.forceRGB = !!forceRGB;
  548. return this.image.getBytes(length);
  549. }
  550. };
  551. return PDFImage;
  552. }();
  553. exports.PDFImage = PDFImage;