-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpnm.js
62 lines (50 loc) · 1.49 KB
/
pnm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import {lazystream} from '../util.js';
const MIME_TYPES = {
['PF']: 'application/x-font-type1',
['P1']: 'image/x-portable-bitmap',
['P2']: 'image/x-portable-graymap',
['P3']: 'image/x-portable-pixmap',
['P4']: 'image/x-portable-bitmap',
['P5']: 'image/x-portable-graymap',
['P6']: 'image/x-portable-pixmap',
['P7']: 'image/x-portable-arbitrarymap',
};
export function readMediaAttributes(input) {
const stream = lazystream(input);
const type = stream.take(3).toString().trim();
const attrs = type === 'P7' ? pam(stream) : pnm(stream);
const result = {
...attrs,
size: stream.size(),
mime: MIME_TYPES[type],
};
stream.close();
return result;
}
function pnm(stream) {
while (stream.more()) {
const line = stream.takeLine().toString();
if (line.match(/^\d+\s+\d+/)) {
const [widthString, heightString] = line.split(/\s+/);
return {
width: parseInt(widthString),
height: parseInt(heightString),
};
}
}
}
function pam(stream) {
const result = {width: 0, height: 0};
while (stream.more()) {
const [key, stringSize] = stream
.takeLine()
.toString()
.toLowerCase()
.split(/\s+/i);
if (key === 'width' || key === 'height') {
result[key] = parseInt(stringSize);
if (result.width && result.height) break;
}
}
return result;
}