繁体   English   中英

如何在Meteor的服务器端生成图像并通过Iron Router提供它们?

[英]How to generate images server-side in Meteor and serve them via Iron Router?

就像标题所说的那样,我只想在服务器上生成图像,然后通过Iron Router在浏览器中提供它。

这是我到目前为止的内容:

server / methods.js

Meteor.methods({
  getImage(cardId, styleId) {
    var canvas = new Canvas(500, 200);
    var ctx = canvas.getContext('2d');

    ctx.font = '26px "Comic Sans"';
    ctx.fillText('Hello World', 50, 80);

    var buffer = canvas.toBuffer();
    buffer = canvas.toDataURL();

    return buffer;
  }
});

route / routes.js

Router.route('/i/:cardid/:styleid.png', function() {
  var imgContent = Meteor.call('getImage', this.params.cardid, this.params.styleid);
  //imgContent = `<html><body><img src="${imgContent}"></body></html>`;

  this.response.writeHeader('200', {
    'Content-Type': 'image/png',
    'Content-Length': imgContent.length
  });

  this.response.write(imgContent);

  this.response.end();
}, {where: 'server'});

如果我取消注释route.js中的行并注释掉image/png标头,则可以将图像显示在HTML图像标签内,但这不是我想要的,因为我只想提供实际的图像,没有HTML。

任何帮助将不胜感激。 谢谢!

编辑我也尝试返回此:

var buffer = canvas.toBuffer();
//buffer = canvas.toDataURL();

buffer = new Buffer(buffer, 'binary').toString('base64');

没有成功。

没有image / png标头的文件内容

具有image / png标题的文件内容

编辑2基本上我正在尝试做到这一点: NodeJS:服务由节点画布生成的png,但仅具有流星,画布和铁路由器。

我考虑了一下。 您可以在onAfterAction()简单地执行以下onAfterAction()

document.type="img";
document.location=url;

但是,这样做会丢失路由器。

您仍然会在结果页面中看到html,因为如果您在浏览器中打开图片的网址,则会在其周围自动添加自己的html标记。 为了证明这一点,只需右键单击此处的图像,然后选择“在新选项卡中打开图像”

您可以将Picker用于服务器端路由,因为它实现了Node的ServerResponse模块[ https://nodejs.org/api/http.html#http_class_http_serverresponse][1] [ https://github.com/meteorhacks/picker/][1 ]

    Picker.route('/i/:cardid/:styleid.png', function(params, req, res, next) {
       var imgContent = Meteor.call('getImage', params.cardid, params.styleid);

  res.writeHead('200', {
    'Content-Type': 'image/png',
    'Content-Length': imgContent.length
  });

 res.end(imgContent);
    });

我可以通过执行以下操作使其工作:

server / methods.js

Meteor.methods({
  getImage(cardId, styleId) {
    var canvas = new Canvas(500, 200);
    var ctx = canvas.getContext('2d');

    ctx.font = '26px "Comic Sans"';
    ctx.fillText('Hello World', 50, 80);

    return canvas.toBuffer();
  }
});

路线/routes.js

Router.route('/i/:cardid/:styleid.png', function() {
  var imgContent = Meteor.call('getImage', this.params.cardid, this.params.styleid);
  imgContent = new Buffer(imgContent, 'binary');

  this.response.writeHeader('200', {
    'Content-Type': 'image/png',
    'Content-Length': imgContent.length
  });

  this.response.write(imgContent);

  this.response.end();
}, {where: 'server'});

基本上只需要输出正确的数据即可!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM