diff --git a/README.md b/README.md index 38895e7..533a0a4 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,17 @@ The api same as base64, but it's synchronous var data = base64Img.base64Sync('path/demo.png'); ``` +### .requestBase64(url, callback) +* {string} ``url`` required +* {function} ``callback(err, res, body)`` required +Callback with http request +```js +var url = 'http://../demo.png'; +base64Img.requestBase64(url, function(err, res, body) { + +}); +``` + ### .img(data, destpath, name, callback) Convert image base64 data to image * {string} ``data`` required diff --git a/base64-img.js b/base64-img.js index 8d9e938..10bb7c3 100644 --- a/base64-img.js +++ b/base64-img.js @@ -1,5 +1,6 @@ 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); @@ -55,6 +56,29 @@ exports.base64Sync = function(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 diff --git a/package.json b/package.json index 080b78e..977591d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "base64-img", - "version": "1.0.1", + "version": "1.0.2", "description": "Convert img to base64, or convert base64 to img", "main": "base64-img.js", "scripts": { @@ -23,6 +23,7 @@ }, "homepage": "https://github.com/douzi8/base64-img", "dependencies": { + "ajax-request": "^1.1.0", "file-system": "^2.1.0" }, "devDependencies": { diff --git a/test/index.js b/test/index.js index 42fb4ea..9717ed2 100644 --- a/test/index.js +++ b/test/index.js @@ -52,5 +52,21 @@ describe('Test', function() { var filepath = base64Img.imgSync(data, getpath('dest'), '3'); assert.equal('.jpg', path.extname(filepath)); }); + + it('request', function(done) { + var url = 'http://webresource.c-ctrip.com/ResCRMOnline/R5/html5/images/57.png'; + var demo = readFileSync('img/demo.png'); + var data = base64Img.base64Sync(getpath('img/demo.png')); + + base64Img.requestBase64(url, function(err, res, body) { + if (err) { + done(); + return console.log(err); + } + + assert.equal(body.substr(0, 10), data.substr(0, 10)); + done(); + }); + }); }); }); \ No newline at end of file