使用Node创建的映像响应GET请求

时间:2015-07-27 22:12:34

标签: javascript node.js http canvas

我有一个简单的Node Api,它接受GET请求,使用node canvas构建画布,将其保存为PNG,然后将其发送回服务器。我可以保存它,但我无法将其保存到服务器。路由器是:

router.get('/canvas', function(req, res) {

    var callback = function(data){

         res.writeHead(200, {'Content-Type': 'text/html'});
          res.write('<img src="data:image/jpeg;base64,')
          res.write(new Buffer(data).toString('base64'));
          res.end('"/>');
    };

    canvas.getCanvas(callback);

});

Node模型是:

  var getCanvas = function(callback){

    var Canvas = require('canvas'),
    canvas = new Canvas(150, 150),
    ctx = canvas.getContext('2d'),
    fs = require('fs');


    ctx.font = '30px Impact';
    ctx.rotate(.1);
    ctx.fillText("Awesome!", 50, 100);

    var te = ctx.measureText('Awesome!');
    ctx.strokeStyle = 'rgba(0,0,0,0.5)';
    ctx.beginPath();
    ctx.lineTo(50, 102);
    ctx.lineTo(50 + te.width, 102);
    ctx.stroke();


    var out = fs.createWriteStream(__dirname + '/text2.png'),
        stream = canvas.pngStream();


    stream.on('data', function(chunk){
      out.write(chunk);
    });

    stream.on('end', function(){
      console.log('saved png');
      fs.readFile(__dirname +'/text2.png', function(err, data) {

          if (err) throw err; // Fail if the file can't be read.

            callback(data);
        });
    });

  }

module.exports.getCanvas = getCanvas;

PNG会保存到文件系统,但在浏览器中对GET请求的响应我只看到:

<img src="data:image/jpeg;base64,iVBORw0KGgo="/>

大小只有370字节,因此浏览器显然没有收到图像。如何将此图像作为对GET请求的响应发回?还有一个相关的问题,我是否需要将其保存到文件系统中,还是可以在图像创建后以某种方式将图像流回来?

1 个答案:

答案 0 :(得分:1)

而不是写入文件,然后读取所述文件,将块添加到数组中,然后将其连接到缓冲区,所以更改:

stream.on('data', function(chunk){
  out.write(chunk);
});

var chunks = [];
stream.on('data', function(chunk){
  out.write(chunk); //remove this if you have no need to keep file local
  chunks.push(chunk);
});

然后改变你的结果:

stream.on('end', function(){
  console.log('saved png');
  callback(Buffer.concat(chunks));
});

由于您的回调现在接受缓冲区,因此也要更改此位:

var callback = function(data){

     res.writeHead(200, {'Content-Type': 'text/html'});
      res.write('<img src="data:image/jpeg;base64,')
      res.write(data.toString('base64'));
      res.end('"/>');
};