image.js 18 KB

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