首页 > 解决方案 > nodejs base64 图像响应不是作为图像对象出现的。添加标题时 {'Content-Type': 'image/jpeg or png'}

问题描述

当我在服务器端生成图像并获取 base64 图像字符串时。

我想作为图像对象发送。它通过创建图像流与节点画布正常工作。

    let stream = this.canvas.jpegStream({progressive: true});

    this.res.writeHead(200, {
        'Content-Type': 'image/jpeg'
    });
    stream.on('data', (chunk) => {
        this.res.write(chunk);
    });
    stream.on('end', () => {
        this.res.end(); 
    });
// Working perfectly...!

但是当我使用fabric.js 时,它返回的是直接base64 图像,而不是像node-canvas 这样的base64 流。当我发送 base64 作为响应时,图像变为空白。

    this.res.writeHead(200, {
        'Content-Type': 'image/png'
    });
    this.res.write(this.fabricCanvas.toDataURL());
    this.res.end();

标签: node.jsfabricjsnode-canvas

解决方案


Content-Type: image/png不是与data:URL 一起使用的正确标头。

您可以尝试以下方法之一:

// Preferred: returns a PNG-encoded image buffer
this.fabricCanvas.toBuffer()

// Wasteful - goes from binary to base64 and back
Buffer.from(this.fabricCanvas.toDataURL().split(",")[1], "base64")

推荐阅读