modules/jpeg_support.js

  1. /* global jsPDF */
  2. /**
  3. * @license
  4. *
  5. * Licensed under the MIT License.
  6. * http://opensource.org/licenses/mit-license
  7. */
  8. /**
  9. * jsPDF jpeg Support PlugIn
  10. *
  11. * @name jpeg_support
  12. * @module
  13. */
  14. (function (jsPDFAPI) {
  15. 'use strict';
  16. /**
  17. * 0xc0 (SOF) Huffman - Baseline DCT
  18. * 0xc1 (SOF) Huffman - Extended sequential DCT
  19. * 0xc2 Progressive DCT (SOF2)
  20. * 0xc3 Spatial (sequential) lossless (SOF3)
  21. * 0xc4 Differential sequential DCT (SOF5)
  22. * 0xc5 Differential progressive DCT (SOF6)
  23. * 0xc6 Differential spatial (SOF7)
  24. * 0xc7
  25. */
  26. var markers = [0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7];
  27. //takes a string imgData containing the raw bytes of
  28. //a jpeg image and returns [width, height]
  29. //Algorithm from: http://www.64lines.com/jpeg-width-height
  30. var getJpegInfo = function (imgData) {
  31. var width, height, numcomponents;
  32. var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
  33. var len = imgData.length;
  34. var result = { width: 0, height: 0, numcomponents: 1 };
  35. for (var i = 4; i < len; i += 2) {
  36. i += blockLength;
  37. if (markers.indexOf(imgData.charCodeAt(i + 1)) !== -1) {
  38. height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
  39. width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
  40. numcomponents = imgData.charCodeAt(i + 9);
  41. result = { width: width, height: height, numcomponents: numcomponents };
  42. break;
  43. } else {
  44. blockLength = imgData.charCodeAt(i + 2) * 256 + imgData.charCodeAt(i + 3);
  45. }
  46. }
  47. return result;
  48. };
  49. /**
  50. * @ignore
  51. */
  52. jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString, colorSpace) {
  53. var filter = this.decode.DCT_DECODE,
  54. bpc = 8,
  55. dims,
  56. result = null;
  57. if (typeof data === 'string' || this.__addimage__.isArrayBuffer(data) || this.__addimage__.isArrayBufferView(data)) {
  58. // if we already have a stored binary string rep use that
  59. data = dataAsBinaryString || data;
  60. data = (this.__addimage__.isArrayBuffer(data)) ? new Uint8Array(data) : data;
  61. data = (this.__addimage__.isArrayBufferView(data)) ? this.__addimage__.arrayBufferToBinaryString(data) : data;
  62. dims = getJpegInfo(data);
  63. switch (dims.numcomponents) {
  64. case 1:
  65. colorSpace = this.color_spaces.DEVICE_GRAY;
  66. break;
  67. case 4:
  68. colorSpace = this.color_spaces.DEVICE_CMYK;
  69. break;
  70. case 3:
  71. colorSpace = this.color_spaces.DEVICE_RGB;
  72. break;
  73. }
  74. result = { data: data, width: dims.width, height: dims.height, colorSpace: colorSpace, bitsPerComponent: bpc, filter: filter, index: index, alias: alias };
  75. }
  76. return result;
  77. };
  78. })(jsPDF.API);