image.js 19 KB

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