我想从 url 获取图像并通过 nodejs 对该图像进行 base64 编码,然后通过 base64 编码显示该图像,但此代码不正确。 此代码保存不正确的 png 文件。
var http = require('http')
, fs = require('fs')
, options
options = {
host: 'google.com'
, port: 80
, path: '/images/srpr/logo3w.png'
}
function base64_encode(bitmap) {
return new Buffer(bitmap).toString('base64');
}
function ImageReady(res2){
var request = http.get(options, function(res){
var imagedata = '';
res.setEncoding('binary');
res.on('data', function(chunk){
imagedata += chunk;
})
res.on('end', function(){
var base64encode = base64_encode(imagedata);
res2.end('<img src="data:image/png;base64,'+base64encode+'" />');
fs.writeFile('logo.png', imagedata, 'binary', function(err){
if (err) throw err
console.log('File saved.')
})
})
})
}
var httpListen = require('http');
httpListen.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
ImageReady(res);
}).listen(8080);
console.log('Server running!');
最佳答案
试试这个:
var loadBase64Image = function (url, callback) {
// Required 'request' module
var request = require('request');
// Make request to our image url
request({url: url, encoding: null}, function (err, res, body) {
if (!err && res.statusCode == 200) {
// So as encoding set to null then request body became Buffer object
var base64prefix = 'data:' + res.headers['content-type'] + ';base64,'
, image = body.toString('base64');
if (typeof callback == 'function') {
callback(image, base64prefix);
}
} else {
throw new Error('Can not download image');
}
});
};
在您的 node.js 应用程序中使用:
// ...
loadBase64Image('http://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Carcharhinus_falciformis_off_Cuba.jpg/180px-Carcharhinus_falciformis_off_Cuba.jpg', function (image, prefix) {
res.send('<img src="' + prefix + image + '"') />;
});
// ...
关于node.js - 从另一个域获取图像并通过 Node js 进行 base64 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11280063/