forked from fuzhenn/node-svg2img
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
189 lines (179 loc) · 5.71 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
var canvg = require('canvg'),
atob = require('atob'),
fs = require('fs'),
http = require('http'),
https = require('https'),
Canvas = require('canvas');
/**
* Main method
* @param {String} svg - a svg string, or a base64 string starts with "data:image/svg+xml;base64", or a file url (http or local)
* @param {Object} [options=null] - options
* @param {Object} [options.format=png] - format of the image: png or jpeg, default is png
* @param {Function} callback - result callback, 2 parameters: error, and result buffer in png
*/
function svg2img(svg, options, callback) {
if (isFunction(options)) {
callback = options;
options = null;
}
if (!options) {
options = {};
}
loadSVGContent(svg, function(error, content) {
if (error) {
callback(error);
return;
}
if (options.width || options.height) {
content = scale(content, options.width, options.height);
}
var format = options.format;
if (!format) {
format = 'png';
}
var canvas = convert(content, options);
var stream;
if (format === 'jpg' || format === 'jpeg') {
stream = canvas.jpegStream({
quality: options['quality'] // JPEG quality (0-100) default: 75
});
} else {
stream = canvas.pngStream();
}
var data = [];
var pos = 0;
stream.on('data', function(chunk) {
data.push(chunk);
});
stream.on('error', function(error) {
callback(error);
});
stream.on('end', function () {
callback(null,Buffer.concat(data));
});
});
}
function convert(svgContent) {
var canvas = new Canvas();
canvg(canvas, svgContent, { ignoreMouse: true, ignoreAnimation: true, ImageClass: Canvas.Image });
return canvas;
}
function scale(svgContent, w, h) {
var index = svgContent.indexOf('<svg');
var svgTag = [];
var endIndex = index;
for (var i = index; i < svgContent.length; i++) {
var char = svgContent.charAt(i);
svgTag.push(char);
if (char === '>') {
endIndex = i;
break;
}
}
svgTag = svgTag.join('').replace(/\n/g, ' ').replace(/\r/g, '');
var props = {};
var splits = svgTag.substring(4, svgTag.length-1).split(' ');
var lastKey;
var i;
for (i = 0; i < splits.length; i++) {
if (splits[i] === '') {
continue;
} else {
if (splits[i].indexOf('=') < 0) {
props[lastKey] = props[lastKey]+' '+splits[i];
} else {
var keyvalue = splits[i].split('=');
lastKey = keyvalue[0];
props[lastKey] = keyvalue[1];
}
}
}
var ow = props['width'] ? parseInt(props['width'].replace('"',''), 10) : null,
oh = props['height'] ? parseInt(props['height'].replace('"',''), 10) : null;
if (w) {
props['width'] = '"'+w+'"';
}
if (h) {
props['height'] = '"'+h+'"';
}
if (!props['viewBox']) {
props['viewBox'] = '"'+[0,0,ow?ow:w,oh?oh:h].join(' ')+'"';
}
props['preserveAspectRatio'] = '"none"';
// update width and height in style attribute
if (props['style'] && props['style'].length > 2) {
var styleUpdated = false;
var styleStr = props['style'].substring(1, props['style'].length - 1);
var styles = styleStr.split(';');
for (var i = 0; i < styles.length; i++) {
var styleKV = styles[i].split(':');
if (styleKV.length === 2) {
var key = styleKV[0].trim();
if (key === 'width') {
styles[i] = 'width : ' + w +'px';
styleUpdated = true;
} else if (key === 'height') {
styles[i] = 'height : ' + h +'px';
styleUpdated = true;
}
}
}
if (styleUpdated) {
props['style'] = '"' + styles.join(';') + '"';
}
}
var newSvgTag = ['<svg'];
for (var p in props) {
newSvgTag.push(p+'='+props[p]);
}
newSvgTag.push('>');
return svgContent.substring(0, index)+newSvgTag.join(' ')+svgContent.substring(endIndex+1);
}
function loadSVGContent(svg, callback) {
if (Buffer.isBuffer(svg)) {
svg = svg.toString('utf-8');
}
if (svg.indexOf('data:image/svg+xml;base64,') >= 0) {
callback(null,atob(svg.substring('data:image/svg+xml;base64,'.length)));
} else if (svg.indexOf('<svg') >= 0) {
callback(null, svg);
} else {
if (svg.indexOf('http://')>=0 || svg.indexOf('https://')>=0) {
loadRemoteImage(svg, callback);
} else {
fs.readFile(svg, function(error, data) {
if (error) {
callback(error);
return;
}
callback(null, data.toString('utf-8'));
});
}
}
}
function loadRemoteImage(url, onComplete) {
//http
var loader;
if (url.indexOf('https://') >= 0) {
loader = https;
} else {
loader = http;
}
loader.get(url, function(res) {
var data = [];
res.on('data', function(chunk) {
data.push(chunk)
});
res.on('end', function () {
var content = Buffer.concat(data).toString('utf-8');
onComplete(null, content);
});
}).on('error', onComplete);
}
function isFunction(func) {
if (!func) {
return false;
}
return typeof func === 'function' || (func.constructor!==null && func.constructor == Function);
}
exports = module.exports = svg2img;