gpt4 book ai didi

google-cloud-functions - 将 base64 图像字符串传递给调用 Cloud Vision API 的 Firebase 可调用云函数

转载 作者:行者123 更新时间:2023-12-04 09:25:54 28 4
gpt4 key购买 nike

我正在实现一个 Web 应用程序,它使用 Cloud Vision API 来检测用户生成的图像上的文本。
我正在使用 React 和 Firebase 云函数。
流程如下:

  • 用户从图库或相机获取图像,使用 react-image-crop 裁剪它包裹
  • 此软件包使用 <canvas>用于生成裁剪图像的元素
  • 我正在将图像转换为 base64使用 canvas.toDataURL("image/jpeg",1.0);
  • 我正在通过 imageBase64字符串到云函数
  • cloud函数需要读取图片并调用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图像似乎正确生成。
    enter image description here
    来自 Node.js Vision API 上的 Google 文档:
    https://googleapis.dev/nodejs/vision/latest/v1.ImageAnnotatorClient.html#textDetection
    我们明白了:
    enter image description here
    尝试使用缓冲区时,我收到 no image present并通过 base64我得到的字符串 code: ENAMETOOLONG 问题
    我应该如何转换 base64将字符串转换为 Cloud Vision API 将接受的内容?

    最佳答案

    我就是这样解决的。
    我打开了一个 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
    enter image description here
    但我从另一篇文档中得到了这个想法:
    https://cloud.google.com/vision/docs/base64
    enter image description here

    关于google-cloud-functions - 将 base64 图像字符串传递给调用 Cloud Vision API 的 Firebase 可调用云函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63011231/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com