从另一个域获取图像并按节点js编码base64

时间:2012-07-01 06:39:09

标签: node.js base64 encode

我想从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!');

4 个答案:

答案 0 :(得分:11)

试试这个:

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 + '"') />;
});
// ...

答案 1 :(得分:1)

尝试使用request npm插件

app.get('/', function(req, res){
  if(req.param("url")) {
    var url = unescape(req.param("url"));
    var bl = new BufferList();
    request({uri:url, responseBodyStream: bl}, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        var data_uri_prefix = "data:" + response.headers["content-type"] + ";base64,";
        var image = new Buffer(bl.toString(), 'binary').toString('base64');                                                                                                                                                                 
        image = data_uri_prefix + image;
        res.send('<img src="'+image+'"/>');
      }
    }); 
  }
});

更多信息:https://gist.github.com/583836

答案 2 :(得分:1)

我尝试使用@ codef0rmer代码,但没有成功......在阅读了gist评论之后,我偶然发现了一个不依赖于“BufferList”外部库并且作为魅力的解决方案......

所以继承人link for this gist!它用咖啡写成,全部归功于@hackable

express = require("express")
request = require("request")
BufferList = require("bufferlist").BufferList //no longer needed
app = express.createServer(express.logger(), express.bodyParser())
app.get "/", (req, res) ->
  if req.param("url")
    url = unescape(req.param("url"))
    request
      uri: url
      encoding: 'binary'
    , (error, response, body) ->
      if not error and response.statusCode is 200
      data_uri_prefix = "data:" + response.headers["content-type"] + ";base64,"
        image = new Buffer(body.toString(), "binary").toString("base64")
        image = data_uri_prefix + image
        res.send "<img src=\"" + image + "\"/>"

app.listen 3000

答案 3 :(得分:0)

我最近遇到了这种情况,仅通过使用此模块base64-img就可以克服它 只需从网址中提取base64编码的图像


var base64Img = require('base64-img');

base64Img.requestBase64(url, function (err, res, body) {
    if (err) console.log(err)
    else {
        console.log(res)
        console.log(body)  
    }
});