小编use*_*931的帖子

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

我想从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, …
Run Code Online (Sandbox Code Playgroud)

base64 encode node.js

2
推荐指数
1
解决办法
9696
查看次数

标签 统计

base64 ×1

encode ×1

node.js ×1