image.js 19 KB

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