【问题标题】:How can I transform a canvas object into an image to send as an API response?如何将画布对象转换为图像以作为 API 响应发送?
【发布时间】:2021-11-01 05:44:35
【问题描述】:

所以我有一个与canvas 模块一起使用的自定义节点模块(无浏览器交互)。

我正在构建一个 expressjs 网络服务器,它有一个应该返回图像的端点。这个 expressjs 应用可以访问我的自定义模块,并且可以从中检索画布对象。

我的问题是 - 我究竟如何将画布转换为 png,然后将其作为响应发送,而不实际将画布保存为服务器中的 png?从stackoverflow上的other related questions,我看到发送图像作为响应就像使用res.sendFile()函数一样简单,但问题是我实际上没有.png文件,我也不想转换画布到png,保存在服务器上,然后发送。一定有可能以某种方式以编程方式执行此操作。

这是一个端点的代码示例:

app.get('/api/image/:id', async (req, res) => {

    let imageId = req.params.id;
    let customModule = new CustomImage(imageId);
    let imageCanvas = customModule.getCanvas();
    let imageName = customModule.getName();

    // this next step is what I'm trying to avoid
    fs.writeFileSync(`.tmp/${imageName}.png`, imageCanvas.toBuffer("image/png"));

    res.sendFile(`./tmp/${imageName}.png`)
    
} )

谢谢。

【问题讨论】:

    标签: node.js express canvas


    【解决方案1】:

    而不是 res.sendFile 使用这个,它会做的伎俩:

      //create the headers for the response
      //200 is HTTTP status code 'ok'
      res.writeHead(
        200,
        //this is the headers object
        {
          //content-type: image/png tells the browser to expect an image
          "Content-Type": "image/png",
        }
      );
    
      //ending the response by sending the image buffer to the browser
      res.end(imageCanvas.toBuffer("image/png"));
    

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      相关资源
      最近更新 更多