代码之家  ›  专栏  ›  技术社区  ›  betamax

节点.jsbase64对下载的图像进行编码,以便在数据URI中使用

  •  15
  • betamax  · 技术社区  · 14 年前

    var express = require('express'),
    request = require('request'),
    sys = require('sys');
    
    var app = express.createServer(
        express.logger(),
        express.bodyDecoder()
    );
    
    app.get('/', function(req, res){
    
        if(req.param("url")) {
            var url = unescape(req.param("url"));
            request({uri:url}, function (error, response, body) {
              if (!error && response.statusCode == 200) {
    
                    var data_uri_prefix = "data:" + response.headers["content-type"] + ";base64,";
                    var buf = new Buffer(body);
                    var image = buf.toString('base64');
    
                    image = data_uri_prefix + image;
    
                    res.send('<img src="'+image+'"/>');
    
              }
            });
        }
    });
    
    app.listen(3000);
    

    注意:此代码需要“ express “和” request node . 如果您已经安装了npm,它应该像“npm install express”或“npm install request”一样简单。

    不幸的是,这不是预期的工作。如果我用 Google logo

    但是如果我使用在线 Base64 encoder 同样的图像,那么它就完美地工作了。字符串的开头是这样的:

    Ivborw0kgoaaaansuheugaaarmaabfcamaaad8mtmpaaaadadbmveuacwsocrojzitlflowbr+aBiGQFiipCSS8DCm1Cya1FiyNKzexKTjDDSrLDS公司

    我哪里出错了,这是工作不正常?我尝试过很多不同的JSBase64实现,但它们的工作方式都不一样。我唯一能想到的是,我试图将错误的东西转换成base64,但如果是这样的话,我应该转换什么呢?

    3 回复  |  直到 13 年前
        1
  •  13
  •   bxjx    14 年前

    问题是在javascript字符串中编码和存储二进制数据。有一个很好的章节在下面 http://nodejs.org/api.html .

    response.setEncoding('binary'); 就在下面66号线上 var buffer;

    然后我改变了 var buf = new Buffer(body) var buf = new Buffer(body, 'binary'); . 在这之后,一切都很顺利。

    我现在就把它留在这里,但如果你想让我澄清什么,请随时发表评论。

    查看评论。新解决方案 http://gist.github.com/583836

        2
  •  8
  •   JFSIII    13 年前

    以下代码(可在 https://gist.github.com/804225

    var URL = require('url'),
        sURL = 'http://nodejs.org/logo.png',
        oURL = URL.parse(sURL),
        http = require('http'),
        client = http.createClient(80, oURL.hostname),
        request = client.request('GET', oURL.pathname, {'host': oURL.hostname})
    ;
    
    request.end();
    request.on('response', function (response)
    {
        var type = response.headers["content-type"],
            prefix = "data:" + type + ";base64,",
            body = "";
    
        response.setEncoding('binary');
        response.on('end', function () {
            var base64 = new Buffer(body, 'binary').toString('base64'),
                data = prefix + base64;
            console.log(data);
        });
        response.on('data', function (chunk) {
            if (response.statusCode == 200) body += chunk;
        });
    });
    

    还应该生成一个数据URI,而不需要任何外部模块。

        3
  •  0
  •   Steven Spungin    7 年前

    这适用于我使用请求:

    const url = 'http://host/image.png';
    request.get({url : url, encoding: null}, (err, res, body) => {
        if (!err) {
            const type = res.headers["content-type"];
            const prefix = "data:" + type + ";base64,";
            const base64 = body.toString('base64');
            const dataUri = prefix + base64;
        }
    });