forked from douzi8/base64-img
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base64-img.js
109 lines (92 loc) · 2.5 KB
/
base64-img.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
var fs = require('file-system');
var path = require('path');
var request = require('ajax-request');
function base64(filename, data) {
var extname = path.extname(filename).substr(1);
extname = extname || 'png';
return 'data:image/' + extname + ';base64,' + data.toString('base64');
}
function img(data) {
var reg = /^data:image\/(\w+);base64,([\s\S]+)/;
var match = data.match(reg);
var baseType = {
jpeg: 'jpg'
};
if (!match) {
throw new Error('image base64 data error');
}
var extname = baseType[match[1]] ? baseType[match[1]] : match[1];
return {
extname: '.' + extname,
base64: match[2]
};
}
/**
* @description
* Get image file base64 data
* @example
* base64Img.base64('path/demo.png', function(err, data) {})
*/
exports.base64 = function(filename, callback) {
if (!callback) callback = util.noop;
fs.readFile(filename, function(err, data) {
if (err) return callback(err);
callback(null, base64(filename, data));
});
};
/**
* @description
* The api same as base64, but it's synchronous
* @example
* var data = base64Img.base64Sync('path/demo.png');
*/
exports.base64Sync = function(filename) {
var data = fs.readFileSync(filename);
return base64(filename, data);
};
/**
* @description
* Get base64 from url
* @example
* request.base64(
* 'http://webresource.c-ctrip.com/ResCRMOnline/R5/html5/images/57.png',
* function(err, res, body) {
*
* }
* );
*/
exports.requestBase64 = function(url, callback) {
request({
url: url,
isBuffer: true
}, function (err, res, body) {
if (err) return callback(err);
var data = 'data:' + res.headers['content-type'] + ';base64,' + body.toString('base64');
callback(err, res, data);
});
};
/**
* @description
* Convert image base64 data to img
* @example
* base64Img.img('data:image/png;base64,...', 'dest', '1', function(err, filepath) {});
*/
exports.img = function(data, destpath, name, callback) {
var result = img(data);
var filepath = path.join(destpath, name + result.extname);
fs.writeFile(filepath, result.base64, { encoding: 'base64' }, function(err) {
callback(err, filepath);
});
};
/**
* @description
* The api same as img, but it's synchronous
* @example
* var filepath = base64Img.imgSync('data:image/png;base64,...', 'dest', '1');
*/
exports.imgSync = function(data, destpath, name) {
var result = img(data);
var filepath = path.join(destpath, name + result.extname);
fs.writeFileSync(filepath, result.base64, { encoding: 'base64' });
return filepath;
};