-
-
Save patbonecrusher/8f3928498cb28a27dcfed626634cd65d to your computer and use it in GitHub Desktop.
Convert a remote image to Base64-encoded string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Uses [request](https://github.com/mikeal/request) | |
// /?url=http://nodejs.org/logo.png | |
// /?uri=http://nodejs.org/logo.png | |
// /?url=http://nodejs.org/logo.png&cb=cbName | |
// /?url=http://nodejs.org/logo.png&callback=cbName | |
var fs = require('fs'); | |
var url = require('url'); | |
var http = require('http'); | |
var request = require('request'); | |
var port = 8888; | |
var server = http.createServer(function requestListener(httpRequest, httpResponse) { | |
var params = url.parse(httpRequest.url, true).query; | |
var imageURL = params.url || params.uri || params.image; | |
var callbackName = params.callback || params.cb || ''; | |
if (!imageURL) return httpResponse.end(); | |
request( | |
{url: imageURL, encoding: 'binary'}, | |
function onImageResponse(error, imageResponse, imageBody) { | |
if (error) throw error; | |
var imageType = imageResponse.headers['content-type']; | |
var base64 = new Buffer(imageBody, 'binary').toString('base64'); | |
var dataURI = 'data:' + imageType + ';base64,' + base64; | |
var jsonString = JSON.stringify({ | |
code: imageResponse.statusCode, | |
desc: http.STATUS_CODES[imageResponse.statusCode], | |
type: imageType, | |
orig: imageURL, | |
data: dataURI | |
}); | |
var jsonpString = callbackName + '(' + jsonString + ')'; | |
var payload = callbackName ? jsonpString : jsonString; | |
httpResponse.writeHead(imageResponse.statusCode, {'Content-Type': 'application/json'}); | |
httpResponse.write(payload); | |
httpResponse.end(); | |
} | |
); | |
}); | |
server.listen(port); | |
console.log('base64 server created and listening on port', port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment