image.js 17 KB

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