image.js 17 KB

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