-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
61 lines (48 loc) · 1.88 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
58
59
60
61
'use strict';
const path = require('path');
const pify = require('pify');
const gm = require('gm');
const mkdir = require('mkdirp');
const utils = require('./lib/utils');
const platforms = require('./platforms.json');
const mkdirp = pify(mkdir);
module.exports = (file, opts) => {
if (typeof file !== 'string') {
return Promise.reject(new TypeError('Expected a file.'));
}
opts = Object.assign({
platform: '',
dest: process.cwd(),
orientation: 'both',
background: 'white',
contentRatio: 0.8,
draw9patch: true
}, opts);
if (opts.platform === '') {
return Promise.reject(new Error('Please provide a platform'));
}
if (Object.keys(platforms).indexOf(opts.platform.toLowerCase()) === -1) {
return Promise.reject(new Error(`Platform ${opts.platform} is not supported.`));
}
const platform = platforms[opts.platform.toLowerCase()];
const resizeFn = path.extname(file) === '.svg' ? 'density' : 'resize';
const screens = opts.orientation === 'both' ? [].concat(platform.landscape || [], platform.portrait || [], platform.square || []) : [].concat(platform[opts.orientation] || [], platform.square || []);
const img = gm(file);
return pify(img.identify.bind(img))()
.then(identity => {
const {size} = identity;
return Promise.all(screens.map(screen => {
const dest = path.join(opts.dest, screen.name);
const dimension = utils.calculateDimension(size, screen, opts);
const resizeDimension = resizeFn === 'density' ? dimension.dpi : dimension.px;
const image = gm(file)[resizeFn](resizeDimension.width, resizeDimension.height)
.gravity('Center')
.background(opts.background)
.extent(screen.width, screen.height);
return mkdirp(path.dirname(dest))
.then(() => pify(image.write.bind(image))(dest))
.then(() => opts.platform === 'android' && opts.draw9patch && utils.draw9Patch(dest, screen, dimension))
.then(() => dest);
}));
});
};