-
Notifications
You must be signed in to change notification settings - Fork 3
/
createsvg.js
executable file
·125 lines (109 loc) · 2.06 KB
/
createsvg.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/env node
const gm = require('gm')
const fs = require('fs')
const Mustache = require('mustache')
const path = require('path')
const sourcePath = process.argv[2]
const RGBquality = process.argv[3] || 80
const Alphaquality = process.argv[4] || 90
if(!sourcePath) {
console.error('No PNG path provided')
console.warn(`Usage: ${process.argv[1]} path/to/file.png [color quality 0-100 default:80] [alpha quality 0-100 default:90]`)
process.exit(1)
return
}
const AlphaMatrix = [
0,0,0,0,
0,0,0,0,
0,0,0,1,
1,1,1,1
]
const RGBMatrix = [
1,0,0,0,
0,1,0,0,
0,0,1,0,
1,1,1,1
]
/**
* create alpha image
*/
const Alpha = new Promise(
(y, n) => gm(sourcePath)
.recolor(AlphaMatrix)
.quality(Alphaquality)
.toBuffer(`JPEG`, (err, Alphabuffer) => {
if(err) {
return n(err)
}
y(Alphabuffer)
})
)
.catch(console.error)
/**
* create rgb image
*/
const RGB = new Promise(
(y, n) => gm(sourcePath)
.recolor(RGBMatrix)
.quality(RGBquality)
.toBuffer(`JPEG`, (err, RGBbuffer) => {
if(err) {
return n(err)
}
y(RGBbuffer)
})
)
.catch(console.error)
const Dimensions = new Promise(
(y, n) => gm(sourcePath)
.size((err, data) => {
if(err) {
return n(err)
}
y(data)
})
)
Promise.all([
Alpha,
RGB,
Dimensions
])
.then(([
Alpha,
RGB,
Dimensions
]) => {
const RGBUrl = `${sourcePath}.rgb.jpg`
const AlphaURL = `${sourcePath}.a.jpg`
const Data = {
width: String(Dimensions.width),
height: String(Dimensions.height),
RGB: RGB.toString('base64'),
Alpha: Alpha.toString('base64'),
RGBUrl: `./${path.basename(RGBUrl)}`,
AlphaUrl: `./${path.basename(AlphaURL)}`,
}
fs.writeFileSync(
RGBUrl,
RGB
)
fs.writeFileSync(
AlphaURL,
Alpha
)
fs.writeFileSync(
`${sourcePath}.svg`,
Mustache.render(
fs.readFileSync(path.join(__dirname,'template.svg')).toString(),
Data
)
)
fs.writeFileSync(
`${sourcePath}.embed.svg`,
Mustache.render(
fs.readFileSync(path.join(__dirname,'template.embed.svg')).toString(),
Data
)
)
})
.catch(console.error)