image.js 19 KB

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