-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (51 loc) · 1.18 KB
/
index.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
const fs = require('fs');
const path = require('path');
const Jimp = require('jimp');
function readJSON (path) {
return new Promise(function (resolve, reject) {
fs.readFile(path, { encoding: 'utf-8' }, function (err, data) {
if (err) {
reject(err);
} else {
try {
data = JSON.parse(data);
} catch (err) {
return reject(err);
}
resolve(data);
}
});
});
}
module.exports = function (srcJSONPath, srcImgPath, destImgDir, callback) {
const extension = path.extname(srcImgPath);
Promise.all([
Jimp.read(srcImgPath),
readJSON(srcJSONPath)
])
.catch(callback)
.then(function (values) {
const image = values[0];
const json = values[1];
Promise.all(Object.keys(json).map(function (name) {
return new Promise(function (resolve, reject) {
const attrs = json[name];
const filename = path.join(destImgDir, name + extension);
image
.clone()
.crop(attrs.x, attrs.y, attrs.width, attrs.height)
.write(filename, function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}))
.catch(callback)
.then(function () {
callback(null);
});
});
};