【问题标题】:Passing a base64 image string to a Firebase callable cloud function that calls the Cloud Vision API将 base64 图像字符串传递给调用 Cloud Vision API 的 Firebase 可调用云函数
【发布时间】:2020-11-10 15:21:26
【问题描述】:

我正在实现一个使用 Cloud Vision API 检测用户生成图像上的文本的网络应用。

我正在使用 React 和 Firebase 云函数。

流程如下:

  • 用户从图库或相机中获取图像,使用react-image-crop 包对其进行裁剪
  • 此包使用<canvas> 元素来生成裁剪图像
  • 我正在使用canvas.toDataURL("image/jpeg",1.0); 将图像转换为base64
  • 我将 imageBase64 字符串传递给云函数
  • 云端功能需要读取图片并调用 Cloud Vision API

客户代码

const canvasBase64 = canvas.toDataURL("image/jpeg", 1.0);

const result = await firebase.functions().httpsCallable("readTextFromImage")({
  image: canvasBase64
});

setTextareaValue(result.data.text);

云功能代码

const Vision = require('@google-cloud/vision');
const vision = new Vision.ImageAnnotatorClient();

async function readTextFromImage(data)  {

  const imgBase64 = data.image;
  const [textDetections] = await vision.textDetection(imgBase64);

  // OTHER THINGS I'VE TRIED HERE
  
  const buffer = new Buffer(imgBase64, 'base64');
  const arraybuffer  = Uint8Array.from(buffer).buffer;
  const [textDetections] = await vision.textDetection(buffer);
  const [textDetections] = await vision.textDetection(arraybuffer);
}

注意:

base64 图像似乎生成正确。

来自关于 Node.js Vision API 的 Google 文档:

https://googleapis.dev/nodejs/vision/latest/v1.ImageAnnotatorClient.html#textDetection

我们明白了:

在尝试使用缓冲区时,我得到了no image present 并传递了base64 字符串我得到了code: ENAMETOOLONG

问题

我应该如何将base64 字符串转换为 Cloud Vision API 可以接受的字符串?

【问题讨论】:

标签: google-cloud-functions base64 buffer google-cloud-vision arraybuffer


【解决方案1】:

我就是这样解决的。

我打开了一个 Github 问题,详细了解了这个问题。

https://github.com/googleapis/nodejs-vision/issues/808

客户代码

我不得不删除base64 字符串的第一部分。

本部分:"data:image/jpeg;base64,"

const result = await firebase.functions().httpsCallable("readTextFromImage")({
  image: canvasBase64.split("base64,")[1]  // <--- REMOVES THE FIRST PART OF THE STRING
});

云功能代码*

我还必须使用带有{ image: { content: base64String } } 的对象调用 textDetection

const [textDetections] = await vision.textDetection(
  {
    image: {
      content: imgBase64
    }
  }
);

尽管这违反了文档

https://googleapis.dev/nodejs/vision/latest/v1.ImageAnnotatorClient.html#textDetection

但我从另一篇文档中得到了这个想法:

https://cloud.google.com/vision/docs/base64

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 2020-11-10
    • 2023-03-26
    • 2020-10-01
    • 2012-12-04
    • 2021-01-05
    • 2014-05-19
    • 1970-01-01
    • 2020-04-18
    相关资源
    最近更新 更多