node.js - 从另一个域获取图像并通过 Node js 进行 base64 编码

标签 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!');

最佳答案

试试这个:

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/

相关文章:

node.js - 运行 GeddyJS 时如何为 node.js 启用 --debug

node.js - 为什么li标签没有获取循环变量的值?

mongodb - 如何使用Golang在MongoDB中存储UUID?

node.js - Webpack 传输轮询错误

javascript - 如何将日期从 2018-04-29 格式转换为 29 Apr,2018 格式?

PHP - 添加/删除回车到 base 64 编码字符串

java - 捕获图像并显示为 Base64 字符串

java - base64图像编码使用java

java - Python 到 Java 代码 : String. 在 java 中进行编码()

python - 使用 Python 2.7 使用十六进制符号对字符串中的特定字符进行编码/解码