-
Notifications
You must be signed in to change notification settings - Fork 0
/
imagesize.js
87 lines (74 loc) · 1.86 KB
/
imagesize.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// # Rework Imagesize
//
/* jslint node: true */
"use strict";
var imagesize = require('imagesize').Parser;
var visit = require('rework-visit');
var fs = require('fs');
var path = require('path');
var METHODS = ['imgsize', 'imgsizew', 'imgsizeh'];
module.exports = function (dir) {
return function (stylesheet) {
visit(stylesheet, function (declarations, rule) {
var add = [];
declarations.forEach(function (r, index, arr) {
if (METHODS.indexOf(r.property) !== -1) {
var s = size(dir, r.value);
if (s) {
add = setDeclarations(s, r.property);
}
else {
throw new Error(
'Failed to get image size of: '+ path.join(dir, r.value)
);
}
declarations.splice(index, 1);
}
});
add.forEach(function (item) {
declarations.push(item);
});
});
};
};
// @TODO: Could be made smarter by incrementally reading more data as needed
// using fs.readSync();
function size(dir, name) {
var parser = imagesize();
var data = fs.readFileSync(path.join(dir, name));
var result = false;
switch (parser.parse(data)) {
case imagesize.DONE:
result = parser.getResult();
break;
}
return result;
}
function setDeclarations(s, property) {
var add = [];
var getWidth = false;
var getHeight = false;
// This is beutiful code.
var last = property.substr(-1, 1);
switch (last) {
case 'w':
getWidth = true;
break;
case 'h':
getHeight = true;
break;
default:
getWidth = true;
getHeight = true;
break;
}
var d = 'declaration';
if (getWidth) {
add.push({type: d, property: 'width', value: s.width + 'px'});
}
if (getHeight) {
add.push({type: d, property: 'height', value: s.height + 'px'});
}
return add;
}