UNPKG

1.54 kBJavaScriptView Raw
1'use strict';
2
3/* eslint-disable consistent-return */
4
5var readUInt16BE = require('../common').readUInt16BE;
6
7
8module.exports = function (data) {
9 if (data.length < 2) return;
10
11 // first marker of the file MUST be 0xFFD8
12 if (data[0] !== 0xFF || data[1] !== 0xD8) return;
13
14 var offset = 2;
15
16 for (;;) {
17 if (data.length - offset < 2) return;
18 // not a JPEG marker
19 if (data[offset++] !== 0xFF) return;
20
21 var code = data[offset++];
22 var length;
23
24 // skip padding bytes
25 while (code === 0xFF) code = data[offset++];
26
27 // standalone markers, according to JPEG 1992,
28 // http://www.w3.org/Graphics/JPEG/itu-t81.pdf, see Table B.1
29 if ((0xD0 <= code && code <= 0xD9) || code === 0x01) {
30 length = 0;
31 } else if (0xC0 <= code && code <= 0xFE) {
32 // the rest of the unreserved markers
33 if (data.length - offset < 2) return;
34
35 length = readUInt16BE(data, offset) - 2;
36 offset += 2;
37 } else {
38 // unknown markers
39 return;
40 }
41
42 if (code === 0xD9 /* EOI */ || code === 0xDA /* SOS */) {
43 // end of the datastream
44 return;
45 }
46
47 if (length >= 5 &&
48 (0xC0 <= code && code <= 0xCF) &&
49 code !== 0xC4 && code !== 0xC8 && code !== 0xCC) {
50
51 if (data.length - offset < length) return;
52
53 return {
54 width: readUInt16BE(data, offset + 3),
55 height: readUInt16BE(data, offset + 1),
56 type: 'jpg',
57 mime: 'image/jpeg',
58 wUnits: 'px',
59 hUnits: 'px'
60 };
61 }
62
63 offset += length;
64 }
65};