image.js 16 KB

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