bv7_jpeg2array_b

jpeg -> array

目前为 2018-02-20 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/38665/252976/bv7_jpeg2array_b.js

  1. // ==UserScript==
  2. // @name bv7_jpeg2array_b
  3. // @namespace bv7
  4. // @version 0.3
  5. // @description jpeg -> array
  6. // @author bv7
  7. // @grant GM_xmlhttpRequest
  8. // ==/UserScript==
  9.  
  10. class BaseImage {
  11. load(url, onload) {
  12. GM_xmlhttpRequest({
  13. method : 'GET',
  14. url : this.nodesCaptchaImgs[iImg].src,
  15. overrideMimeType: 'text/plain; charset=x-user-defined',
  16. onload : (v) => {
  17. this.data = v.responseText;
  18. this.seek(0);
  19. if (onload) onload(v);
  20. }
  21. });
  22. }
  23. seek(iData = 0) {
  24. this.iData = iData;
  25. }
  26. skip(i) {
  27. this.iData +=i;
  28. }
  29. getUint8() {
  30. return this.iData < this.data.length ? this.data.charCodeAt(this.iData) && 0xff : 0;
  31. }
  32. readUint8() {
  33. return this.iData < this.data.length ? this.data.charCodeAt(this.iData++) && 0xff : 0;
  34. }
  35. readUint16() {
  36. return (this.readUint8() << 8) | this.readUint8();
  37. }
  38. }
  39.  
  40.  
  41. class JpegImage extends BaseImage {
  42. constructor() {
  43. this.dctZigZag = new Int32Array([
  44. 0,
  45. 1, 8,
  46. 16, 9, 2,
  47. 3, 10, 17, 24,
  48. 32, 25, 18, 11, 4,
  49. 5, 12, 19, 26, 33, 40,
  50. 48, 41, 34, 27, 20, 13, 6,
  51. 7, 14, 21, 28, 35, 42, 49, 56,
  52. 57, 50, 43, 36, 29, 22, 15,
  53. 23, 30, 37, 44, 51, 58,
  54. 59, 52, 45, 38, 31,
  55. 39, 46, 53, 60,
  56. 61, 54, 47,
  57. 55, 62,
  58. 63
  59. ]);
  60. this.dctCos1 = 4017 // cos(pi/16)
  61. this.dctSin1 = 799 // sin(pi/16)
  62. this.dctCos3 = 3406 // cos(3*pi/16)
  63. this.dctSin3 = 2276 // sin(3*pi/16)
  64. this.dctCos6 = 1567 // cos(6*pi/16)
  65. this.dctSin6 = 3784 // sin(6*pi/16)
  66. this.dctSqrt2 = 5793 // sqrt(2)
  67. this.dctSqrt1d2 = 2896 // sqrt(2) / 2
  68. }
  69. readDataBlock() {
  70. value = new Array(this.readUint16() - 2);
  71. value.forEach((v, i) => value[i] = this.readUint8());
  72. return value;
  73. }
  74. seekBit() {
  75. this.bitsData = 0;
  76. this.bitsCount = 0;
  77. }
  78. readBit() {
  79. if (this.bitsCount > 0) this.bitsCount--;
  80. else {
  81. this.bitsData = this.readUint8();
  82. if (this.bitsData == 0xFF) {
  83. let nextByte = this.readUint8();
  84. if (nextByte) {
  85. console.log('JpegImage: Error: unexpected marker: ' + ((this.bitsData << 8) | nextByte).toString(16));
  86. return;
  87. }
  88. // unstuff 0
  89. }
  90. this.bitsCount = 7;
  91. }
  92. return (this.bitsData >> this.bitsCount) & 1;
  93. }
  94. prepareComponents(frame) {
  95. frame.maxH = 0;
  96. frame.maxV = 0;
  97. frame.componentsOrder.forEach((v) => {
  98. let component = frame.components[v];
  99. if (frame.maxH < component.h) frame.maxH = component.h;
  100. if (frame.maxV < component.v) frame.maxV = component.v;
  101. });
  102. frame.mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
  103. frame.mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
  104. frame.componentsOrder.forEach((v) => {
  105. let component = frame.components[v];
  106. component.blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
  107. component.blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
  108. component.blocks = [];
  109. let blocksPerLineForMcu = mcusPerLine * component.h;
  110. let blocksPerColumnForMcu = mcusPerColumn * component.v;
  111. for (let i = 0; i < blocksPerColumnForMcu; i++) {
  112. let row = [];
  113. for (let j = 0; j < blocksPerLineForMcu; j++) row.push(new Int32Array(64));
  114. component.blocks.push(row);
  115. }
  116. });
  117. }
  118. buildHuffmanTable(codeLengths, values) {
  119. let length = codeLengths.length;
  120. while (length > 0 && !codeLengths[length - 1]) length--;
  121. let p = {children: [], index: 0};
  122. let code = [p];
  123. for (let i = 0, k = 0, q; i < length; i++) {
  124. for (let j = 0; j < codeLengths[i]; j++, k++) {
  125. p = code.pop();
  126. p.children[p.index] = values[k];
  127. while (p.index > 0) p = code.pop();
  128. p.index++;
  129. code.push(p);
  130. while (code.length <= i) {
  131. code.push(q = {children: [], index: 0});
  132. p.children[p.index] = q.children;
  133. p = q;
  134. }
  135. }
  136. if (i + 1 < length) { // p here points to last code
  137. code.push(q = {children: [], index: 0});
  138. p.children[p.index] = q.children;
  139. p = q;
  140. }
  141. }
  142. return code[0].children;
  143. }
  144. decodeScan(data, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive) {
  145. this.seekBit();
  146. let decodeHuffman = (tree) => {
  147. let node = tree;
  148. let bit;
  149. while ((bit = this.readBit()) !== null) {
  150. node = node[bit];
  151. if (typeof node === 'number') return node;
  152. if (typeof node !== 'object') {
  153. console.log('JpegImage: Error: invalid huffman sequence');
  154. return;
  155. }
  156. }
  157. return null;
  158. };
  159. let receive = (length) => {
  160. let n = 0;
  161. for (; length > 0; length--) {
  162. let bit = this.readBit();
  163. if (bit === null) return;
  164. n = (n << 1) | bit;
  165. }
  166. return n;
  167. };
  168. let receiveAndExtend = (length) => {
  169. let n = receive(length);
  170. return (n >= 1 << (length - 1)) ? n : (n + (-1 << length) + 1);
  171. };
  172. let decodeBaseline = (component, zz) => {
  173. let t = decodeHuffman(component.huffmanTableDC);
  174. let diff = t === 0 ? 0 : receiveAndExtend(t);
  175. zz[0] = (component.pred += diff);
  176. let k = 1;
  177. while (k < 64) {
  178. let rs = decodeHuffman(component.huffmanTableAC);
  179. let s = rs & 15;
  180. let r = rs >> 4;
  181. if (s === 0) {
  182. if (r < 15) break;
  183. else {
  184. k += 16;
  185. continue;
  186. }
  187. } else {
  188. k += r;
  189. zz[dctZigZag[k]] = receiveAndExtend(s);
  190. k++;
  191. }
  192. }
  193. }
  194. let decodeDCFirst = (component, zz) => {
  195. let t = decodeHuffman(component.huffmanTableDC);
  196. let diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
  197. zz[0] = (component.pred += diff);
  198. }
  199. let decodeDCSuccessive = (component, zz) => zz[0] |= this.readBit() << successive;
  200. let eobrun = 0;
  201. let decodeACFirst = (component, zz) => {
  202. if (eobrun > 0) eobrun--;
  203. else {
  204. let k = spectralStart;
  205. while (k <= spectralEnd) {
  206. let rs = decodeHuffman(component.huffmanTableAC);
  207. let s = rs & 15;
  208. let r = rs >> 4;
  209. if (s === 0) {
  210. if (r < 15) {
  211. eobrun = receive(r) + (1 << r) - 1;
  212. break;
  213. } else k += 16;
  214. } else {
  215. k += r;
  216. let z = ;
  217. zz[this.dctZigZag[k]] = receiveAndExtend(s) * (1 << successive);
  218. k++;
  219. }
  220. }
  221. }
  222. };
  223. let successiveACState = 0;
  224. let successiveACNextValue = 0;
  225. let decodeACSuccessive = (component, zz) => {
  226. let k = spectralStart;
  227. let r = 0;
  228. while(k <= spectralEnd) {
  229. let z = dctZigZag[k];
  230. let direction = zz[z] < 0 ? -1 : 1;
  231. switch (successiveACState) {
  232. case 0: // initial state
  233. let rs = decodeHuffman(component.huffmanTableAC);
  234. let s = rs & 15;
  235. r = rs >> 4;
  236. if (s === 0) {
  237. if (r < 15) {
  238. eobrun = receive(r) + (1 << r);
  239. successiveACState = 4;
  240. } else {
  241. r = 16;
  242. successiveACState = 1;
  243. }
  244. } else if (s !== 1) {
  245. console.log('JpegImage: Error: invalid ACn encoding');
  246. return;
  247. } else {
  248. successiveACNextValue = receiveAndExtend(s);
  249. successiveACState = r ? 2 : 3;
  250. }
  251. continue;
  252. case 1: // skipping r zero items
  253. case 2:
  254. if (zz[z]) zz[z] += (this.readBit() << successive) * direction;
  255. else {
  256. r--;
  257. if (r === 0) successiveACState = successiveACState == 2 ? 3 : 0;
  258. }
  259. break;
  260. case 3: // set value for a zero item
  261. if (zz[z]) zz[z] += (this.readBit() << successive) * direction;
  262. else {
  263. zz[z] = successiveACNextValue << successive;
  264. successiveACState = 0;
  265. }
  266. break;
  267. case 4: // eob
  268. if (zz[z]) zz[z] += (this.readBit() << successive) * direction;
  269. break;
  270. }
  271. k++;
  272. }
  273. if (successiveACState === 4) {
  274. eobrun--;
  275. if (eobrun === 0) successiveACState = 0;
  276. }
  277. };
  278. let decodeMcu = (component, decode, mcu, row, col) => decode(
  279. component,
  280. component.blocks[((mcu / frame.mcusPerLine) | 0) * component.v + row][(mcu % frame.mcusPerLine) * component.h + col]
  281. );
  282. let decodeBlock = (component, decode, mcu) => decode(
  283. component,
  284. component.blocks[(mcu / component.blocksPerLine) | 0][mcu % component.blocksPerLine]
  285. );
  286. let decodeFn = frame.progressive ? (
  287. spectralStart === 0 ? (
  288. successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive
  289. ) : (
  290. successivePrev === 0 ? decodeACFirst : decodeACSuccessive
  291. )
  292. ) : decodeBaseline;
  293. let mcu = 0;
  294. let mcuExpected = (components.length == 1) ? (
  295. components[0].blocksPerLine * components[0].blocksPerColumn
  296. ) : (
  297. frame.mcusPerLine * frame.mcusPerColumn
  298. );
  299. if (!resetInterval) resetInterval = mcuExpected;
  300. while (mcu < mcuExpected) {
  301. // reset interval stuff
  302. components.forEach((v) => v.pred = 0);
  303. eobrun = 0;
  304. if (components.length == 1) {
  305. let component = components[0];
  306. for (let n = 0; n < resetInterval; n++, mcu++) decodeBlock(component, decodeFn, mcu);
  307. } else for (let n = 0; n < resetInterval; n++) {
  308. for (let i = 0; i < components.length; i++) {
  309. let component = components[i];
  310. for (let j = 0; j < component.v; j++) for (let k = 0; k < component.h; k++)
  311. decodeMcu(component, decodeFn, mcu, j, k);
  312. }
  313. mcu++;
  314. // If we've reached our expected MCU's, stop decoding
  315. if (mcu === mcuExpected) break;
  316. }
  317. // find marker
  318. this.bitsCount = 0;
  319. let marker = this.readUint16();
  320. if (marker < 0xFFD0 || marker > 0xFFD7) { // !RSTx
  321. this.seek(this.iData - 2);
  322. if (marker < 0xFF00) console.log('JpegImage: Error: marker was not found');
  323. break;
  324. }
  325. }
  326. }
  327. parse() {
  328. this.jfif = null;
  329. this.adobe = null;
  330. let frame;
  331. let resetInterval;
  332. let quantizationTables = [];
  333. let frames = [];
  334. let huffmanTablesAC = [];
  335. let huffmanTablesDC = [];
  336. this.seek(0);
  337. let fileMarker = readUint16();
  338. if (fileMarker != 0xFFD8) { // SOI (Start of Image)
  339. console.log('JpegImage: Error: SOI not found');
  340. return;
  341. }
  342. while ((fileMarker = readUint16()) != 0xFFD9) { // EOI (End of image)
  343. switch(fileMarker) {
  344. case 0xFF00: break;
  345. case 0xFFE0: // APP0 (Application Specific)
  346. case 0xFFE1: // APP1
  347. case 0xFFE2: // APP2
  348. case 0xFFE3: // APP3
  349. case 0xFFE4: // APP4
  350. case 0xFFE5: // APP5
  351. case 0xFFE6: // APP6
  352. case 0xFFE7: // APP7
  353. case 0xFFE8: // APP8
  354. case 0xFFE9: // APP9
  355. case 0xFFEA: // APP10
  356. case 0xFFEB: // APP11
  357. case 0xFFEC: // APP12
  358. case 0xFFED: // APP13
  359. case 0xFFEE: // APP14
  360. case 0xFFEF: // APP15
  361. case 0xFFFE: // COM (Comment)
  362. let appData = this.readDataBlock();
  363. switch(fileMarker){
  364. case 0xFFE0:
  365. if (
  366. appData[0] === 0x4A &&
  367. appData[1] === 0x46 &&
  368. appData[2] === 0x49 &&
  369. appData[3] === 0x46 &&
  370. appData[4] === 0
  371. ) this.jfif = { // 'JFIF\x00'
  372. version : { major: appData[5], minor: appData[6] },
  373. densityUnits: appData[7],
  374. xDensity : (appData[8 ] << 8) | appData[9 ],
  375. yDensity : (appData[10] << 8) | appData[11],
  376. thumbWidth : appData[12],
  377. thumbHeight : appData[13],
  378. thumbData : appData.slice(14, 14 + 3 * appData[12] * appData[13])
  379. };
  380. break;
  381. // TODO APP1 - Exif
  382. case 0xFFEE:
  383. if (
  384. appData[0] === 0x41 &&
  385. appData[1] === 0x64 &&
  386. appData[2] === 0x6F &&
  387. appData[3] === 0x62 &&
  388. appData[4] === 0x65 &&
  389. appData[5] === 0
  390. ) this.adobe = { // 'Adobe\x00'
  391. version : appData[6],
  392. flags0 : (appData[7] << 8) | appData[8],
  393. flags1 : (appData[9] << 8) | appData[10],
  394. transformCode: appData[11]
  395. };
  396. break;
  397. }
  398. break;
  399. case 0xFFDB: // DQT (Define Quantization Tables)
  400. for(let quantizationTablesLength = this.readUint16() - 2; quantizationTablesLength > 0; quantizationTablesLength--) {
  401. let quantizationTableSpec = this.readUint8();
  402. let tableData = new Int32Array(64);
  403. switch(quantizationTableSpec >> 4){
  404. case 0: // 8 bit values
  405. tableData.forEach((v, i) => tableData[this.dctZigZag[i]] = this.readUint8());
  406. break;
  407. case 1: //16 bit
  408. tableData.forEach((v, i) => tableData[this.dctZigZag[i]] = this.readUint16());
  409. break;
  410. default:
  411. console.log('JpegImage: Error: DQT: invalid table spec');
  412. return;
  413. }
  414. quantizationTables[quantizationTableSpec & 15] = tableData;
  415. }
  416. break;
  417. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  418. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  419. case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
  420. this.readUint16(); // skip data length
  421. frame = {
  422. extended : fileMarker === 0xFFC1,
  423. progressive : fileMarker === 0xFFC2,
  424. precision : this.readUint8(),
  425. scanLines : this.readUint16(),
  426. samplesPerLine : this.readUint16(),
  427. components : {},
  428. componentsOrder: new Array(this.readUint8())
  429. };
  430. frame.componentsOrder.forEach((v, i) => {
  431. let componentId = this.readUint8();
  432. let b = this.readUint8();
  433. frame.componentsOrder[i] = componentId;
  434. frame.components[componentId] = {
  435. h : b >> 4,
  436. v : b & 15,
  437. quantizationIdx: this.readUint8()
  438. };
  439. });
  440. this.prepareComponents(frame);
  441. frames.push(frame);
  442. break;
  443. case 0xFFC4: // DHT (Define Huffman Tables)
  444. let huffmanLength = this.readUint16() - 2;
  445. while (huffmanLength > 0) {
  446. let huffmanTableSpec = this.readUint8();
  447. let codeLengths = new Uint8Array(16);
  448. let codeLengthSum = 0;
  449. codeLengths.forEach((v, i) => codeLengthSum += (codeLengths[i] = this.readUint8()));
  450. let huffmanValues = new Uint8Array(codeLengthSum);
  451. huffmanValues.forEach((v, i) => huffmanValues[i] = this.readUint8());
  452. huffmanLength -= 1 + codeLengths.length + huffmanValues.length;
  453. ((huffmanTableSpec >> 4) === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = this.buildHuffmanTable(codeLengths, huffmanValues);
  454. }
  455. break;
  456. case 0xFFDD: // DRI (Define Restart Interval)
  457. this.readUint16(); // skip data length
  458. resetInterval = this.readUint16();
  459. break;
  460. case 0xFFDA: // SOS (Start of Scan)
  461. this.readUint16(); // scanLength
  462. let components = [];
  463. for (let selectorsCount = this.readUint8; selectorsCount > 0; selectorsCount--) {
  464. let component = frame.components[this.readUint8()];
  465. let tableSpec = this.readUint8();
  466. component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
  467. component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
  468. components.push(component);
  469. }
  470. let spectralStart = this.readUint8();
  471. let spectralEnd = this.readUint8();
  472. let successiveApproximation = this.readUint8();
  473. decodeScan(
  474. data,
  475. frame,
  476. components,
  477. resetInterval,
  478. spectralStart,
  479. spectralEnd,
  480. successiveApproximation >> 4,
  481. successiveApproximation & 15
  482. );
  483. break;
  484. case 0xFFFF: // Fill bytes
  485. if (this.getUint8() !== 0xFF) this.skip(-1); // Avoid skipping a valid marker.
  486. break;
  487. default:
  488. this.skip(-2);
  489. let d1 = this.getUint8();
  490. this.skip(-1);
  491. let d0 = this.getUint(8);
  492. // could be incorrect encoding -- last 0xFF byte of the previous
  493. // block was eaten by the encoder
  494. if (d0 == 0xFF && d1 >= 0xC0 && d1 <= 0xFE) break;
  495. else {
  496. console.log('JpegImage: Error: unknown JPEG marker ' + fileMarker.toString(16));
  497. return;
  498. }
  499. }
  500. }
  501.  
  502.  
  503. if (frames.length != 1)
  504. throw new Error("only single frame JPEGs supported");
  505.  
  506. // set each frame's components quantization table
  507. for (var i = 0; i < frames.length; i++) {
  508. var cp = frames[i].components;
  509. for (var j in cp) {
  510. cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
  511. delete cp[j].quantizationIdx;
  512. }
  513. }
  514.  
  515. this.width = frame.samplesPerLine;
  516. this.height = frame.scanLines;
  517. this.jfif = jfif;
  518. this.adobe = adobe;
  519. this.components = [];
  520. for (var i = 0; i < frame.componentsOrder.length; i++) {
  521. var component = frame.components[frame.componentsOrder[i]];
  522. this.components.push({
  523. lines: buildComponentData(frame, component),
  524. scaleX: component.h / frame.maxH,
  525. scaleY: component.v / frame.maxV
  526. });
  527. }
  528.  
  529.  
  530.  
  531.  
  532. }
  533.  
  534.  
  535. parse: function parse(data) {
  536. var offset = 0, length = data.length;
  537. function readUint16() {
  538. var value = (data[offset] << 8) | data[offset + 1];
  539. offset += 2;
  540. return value;
  541. }
  542. function readDataBlock() {
  543. var length = readUint16();
  544. var array = data.subarray(offset, offset + length - 2);
  545. offset += array.length;
  546. return array;
  547. }
  548. function prepareComponents(frame) {
  549. var maxH = 0, maxV = 0;
  550. var component, componentId;
  551. for (componentId in frame.components) {
  552. if (frame.components.hasOwnProperty(componentId)) {
  553. component = frame.components[componentId];
  554. if (maxH < component.h) maxH = component.h;
  555. if (maxV < component.v) maxV = component.v;
  556. }
  557. }
  558. var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
  559. var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
  560. for (componentId in frame.components) {
  561. if (frame.components.hasOwnProperty(componentId)) {
  562. component = frame.components[componentId];
  563. var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
  564. var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
  565. var blocksPerLineForMcu = mcusPerLine * component.h;
  566. var blocksPerColumnForMcu = mcusPerColumn * component.v;
  567. var blocks = [];
  568. for (var i = 0; i < blocksPerColumnForMcu; i++) {
  569. var row = [];
  570. for (var j = 0; j < blocksPerLineForMcu; j++)
  571. row.push(new Int32Array(64));
  572. blocks.push(row);
  573. }
  574. component.blocksPerLine = blocksPerLine;
  575. component.blocksPerColumn = blocksPerColumn;
  576. component.blocks = blocks;
  577. }
  578. }
  579. frame.maxH = maxH;
  580. frame.maxV = maxV;
  581. frame.mcusPerLine = mcusPerLine;
  582. frame.mcusPerColumn = mcusPerColumn;
  583. }
  584. var jfif = null;
  585. var adobe = null;
  586. var pixels = null;
  587. var frame, resetInterval;
  588. var quantizationTables = [], frames = [];
  589. var huffmanTablesAC = [], huffmanTablesDC = [];
  590. var fileMarker = readUint16();
  591. if (fileMarker != 0xFFD8) { // SOI (Start of Image)
  592. throw new Error("SOI not found");
  593. }
  594.  
  595. fileMarker = readUint16();
  596. while (fileMarker != 0xFFD9) { // EOI (End of image)
  597. var i, j, l;
  598. switch(fileMarker) {
  599. case 0xFF00: break;
  600. case 0xFFE0: // APP0 (Application Specific)
  601. case 0xFFE1: // APP1
  602. case 0xFFE2: // APP2
  603. case 0xFFE3: // APP3
  604. case 0xFFE4: // APP4
  605. case 0xFFE5: // APP5
  606. case 0xFFE6: // APP6
  607. case 0xFFE7: // APP7
  608. case 0xFFE8: // APP8
  609. case 0xFFE9: // APP9
  610. case 0xFFEA: // APP10
  611. case 0xFFEB: // APP11
  612. case 0xFFEC: // APP12
  613. case 0xFFED: // APP13
  614. case 0xFFEE: // APP14
  615. case 0xFFEF: // APP15
  616. case 0xFFFE: // COM (Comment)
  617. var appData = readDataBlock();
  618.  
  619. if (fileMarker === 0xFFE0) {
  620. if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&
  621. appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
  622. jfif = {
  623. version: { major: appData[5], minor: appData[6] },
  624. densityUnits: appData[7],
  625. xDensity: (appData[8] << 8) | appData[9],
  626. yDensity: (appData[10] << 8) | appData[11],
  627. thumbWidth: appData[12],
  628. thumbHeight: appData[13],
  629. thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
  630. };
  631. }
  632. }
  633. // TODO APP1 - Exif
  634. if (fileMarker === 0xFFEE) {
  635. if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&
  636. appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
  637. adobe = {
  638. version: appData[6],
  639. flags0: (appData[7] << 8) | appData[8],
  640. flags1: (appData[9] << 8) | appData[10],
  641. transformCode: appData[11]
  642. };
  643. }
  644. }
  645. break;
  646.  
  647. case 0xFFDB: // DQT (Define Quantization Tables)
  648. var quantizationTablesLength = readUint16();
  649. var quantizationTablesEnd = quantizationTablesLength + offset - 2;
  650. while (offset < quantizationTablesEnd) {
  651. var quantizationTableSpec = data[offset++];
  652. var tableData = new Int32Array(64);
  653. if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
  654. for (j = 0; j < 64; j++) {
  655. var z = dctZigZag[j];
  656. tableData[z] = data[offset++];
  657. }
  658. } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
  659. for (j = 0; j < 64; j++) {
  660. var z = dctZigZag[j];
  661. tableData[z] = readUint16();
  662. }
  663. } else
  664. throw new Error("DQT: invalid table spec");
  665. quantizationTables[quantizationTableSpec & 15] = tableData;
  666. }
  667. break;
  668.  
  669. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  670. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  671. case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
  672. readUint16(); // skip data length
  673. frame = {};
  674. frame.extended = (fileMarker === 0xFFC1);
  675. frame.progressive = (fileMarker === 0xFFC2);
  676. frame.precision = data[offset++];
  677. frame.scanLines = readUint16();
  678. frame.samplesPerLine = readUint16();
  679. frame.components = {};
  680. frame.componentsOrder = [];
  681. var componentsCount = data[offset++], componentId;
  682. var maxH = 0, maxV = 0;
  683. for (i = 0; i < componentsCount; i++) {
  684. componentId = data[offset];
  685. var h = data[offset + 1] >> 4;
  686. var v = data[offset + 1] & 15;
  687. var qId = data[offset + 2];
  688. frame.componentsOrder.push(componentId);
  689. frame.components[componentId] = {
  690. h: h,
  691. v: v,
  692. quantizationIdx: qId
  693. };
  694. offset += 3;
  695. }
  696. prepareComponents(frame);
  697. frames.push(frame);
  698. break;
  699.  
  700. case 0xFFC4: // DHT (Define Huffman Tables)
  701. var huffmanLength = readUint16();
  702. for (i = 2; i < huffmanLength;) {
  703. var huffmanTableSpec = data[offset++];
  704. var codeLengths = new Uint8Array(16);
  705. var codeLengthSum = 0;
  706. for (j = 0; j < 16; j++, offset++)
  707. codeLengthSum += (codeLengths[j] = data[offset]);
  708. var huffmanValues = new Uint8Array(codeLengthSum);
  709. for (j = 0; j < codeLengthSum; j++, offset++)
  710. huffmanValues[j] = data[offset];
  711. i += 17 + codeLengthSum;
  712.  
  713. ((huffmanTableSpec >> 4) === 0 ?
  714. huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
  715. buildHuffmanTable(codeLengths, huffmanValues);
  716. }
  717. break;
  718.  
  719. case 0xFFDD: // DRI (Define Restart Interval)
  720. readUint16(); // skip data length
  721. resetInterval = readUint16();
  722. break;
  723.  
  724. case 0xFFDA: // SOS (Start of Scan)
  725. var scanLength = readUint16();
  726. var selectorsCount = data[offset++];
  727. var components = [], component;
  728. for (i = 0; i < selectorsCount; i++) {
  729. component = frame.components[data[offset++]];
  730. var tableSpec = data[offset++];
  731. component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
  732. component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
  733. components.push(component);
  734. }
  735. var spectralStart = data[offset++];
  736. var spectralEnd = data[offset++];
  737. var successiveApproximation = data[offset++];
  738. var processed = decodeScan(data, offset,
  739. frame, components, resetInterval,
  740. spectralStart, spectralEnd,
  741. successiveApproximation >> 4, successiveApproximation & 15);
  742. offset += processed;
  743. break;
  744.  
  745. case 0xFFFF: // Fill bytes
  746. if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
  747. offset--;
  748. }
  749. break;
  750.  
  751. default:
  752. if (data[offset - 3] == 0xFF &&
  753. data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
  754. // could be incorrect encoding -- last 0xFF byte of the previous
  755. // block was eaten by the encoder
  756. offset -= 3;
  757. break;
  758. }
  759. throw new Error("unknown JPEG marker " + fileMarker.toString(16));
  760. }
  761. fileMarker = readUint16();
  762. }
  763. if (frames.length != 1)
  764. throw new Error("only single frame JPEGs supported");
  765.  
  766. // set each frame's components quantization table
  767. for (var i = 0; i < frames.length; i++) {
  768. var cp = frames[i].components;
  769. for (var j in cp) {
  770. cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
  771. delete cp[j].quantizationIdx;
  772. }
  773. }
  774.  
  775. this.width = frame.samplesPerLine;
  776. this.height = frame.scanLines;
  777. this.jfif = jfif;
  778. this.adobe = adobe;
  779. this.components = [];
  780. for (var i = 0; i < frame.componentsOrder.length; i++) {
  781. var component = frame.components[frame.componentsOrder[i]];
  782. this.components.push({
  783. lines: buildComponentData(frame, component),
  784. scaleX: component.h / frame.maxH,
  785. scaleY: component.v / frame.maxV
  786. });
  787. }
  788. },
  789.  
  790. }
  791.  
  792. class Jpeg {
  793. decode(jpegData) {
  794. }
  795. }
  796.  
  797. jpeg = new Jpeg();