如何在 JSON 响应中嵌入图像

how to embed an image in a JSON response

我正在使用 Jimp 读取 JSON 字符串,如下所示:

如您所见,image 节点是 base64 编码的 JPEG。

我能够成功将其转换为 TIFF 并保存:

  Jimp.read(Buffer.from(inputImage, "base64"), function(err, image) {
    image.getBuffer(Jimp.MIME_TIFF, function(error, tiff) {
    context.bindings.outputBlob = tiff
    ...}

但是,当我尝试将 tiff 嵌入到 JSON 对象中时,TIFF 全部乱码:

  const response = {
    image: tiff.toString('base64'),
    correlation: correlation
  };

  context.bindings.outputBlob = response;

完整代码如下:

const Jimp = require("jimp");

module.exports = function(context, myBlob) {
  const correlation = context.bindings.inputBlob.correlation;
  const inputImage = context.bindings.inputBlob.image;
  const imageName = context.bindings.inputBlob.imageName;

  context.log(
    correlation + "Attempting to convert this image to a tiff: " + imageName
  );
  Jimp.read(Buffer.from(inputImage, "base64"), function(err, image) {
    image.getBuffer(Jimp.MIME_TIFF, function(error, tiff) {
      const response = {
        image: tiff.toString('base64'),
        correlation: correlation
      };

      context.bindings.outputBlob = response;
      context.log(
        correlation + "Succesfully converted " + imageName + " to tiff."
      );
      context.done();
    });
  });
};

我们如何将 tiff 嵌入到 JSON 有效负载中?

如果此输出是不可协商的,我将如何从保存的有效负载中呈现 tiff?

好吧,既然你确认你正在寻找 context.res 的输出,这是我的工作示例。请注意,有最大响应大小,所以你不能 return 每 [=15] =] 我return在此处拍摄图片的方式

const Jimp = require('jimp')

module.exports = async function (context, req)
{
    let response = {}

    try
    {
        let url = 'https://noahwriting.com/wp-content/uploads/2018/06/APPLE-300x286.jpg'

        //call function to download and resize image
        response = await resizeImage(url)

    }
    catch (err)
    {
        response.type = 'application/json'
        if (err.response == undefined)
        {
            context.log(err)
            response.status = 500
            response.data = err
        }
        else
        {
            response.data = err.response.data
            response.status = err.response.status
            context.log(response)
        }
    }

    //response
    context.res =
    {
        headers: { 'Content-Type': `${response.type}` },
        body: response.buf
    }
}

async function resizeImage(url)
{
    //read image to buffer
    let image = await Jimp.read(url)

    //resize image
    image.resize(300, Jimp.AUTO)

    //save to buffer
    let image_buf = await image.getBufferAsync(image.getMIME())

    //image.getMIME() returns something like `image/jpeg` which is a valid Content-Type for responses.
    return { 'buf': image_buf, 'type': image.getMIME() }
}

(Offtopic 但我看到你正在使用 blob 存储所以..)如果你计划在 Azure Blob 存储中存储 photos/files/anything 并且你想以某种系统的方式检索它们你会很快发现你不能查询存储,你必须处理丑陋的 XML。我的解决方法是避免以这种方式创建一个函数,该函数将 photos/files 存储在 Blob 存储中,然后将 url 路径连同文件名和任何其他属性保存到 mongo贮存。这样我就可以进行超快速查询来检索指向相应文件的链接数组。