首页 > 解决方案 > 如何使用 React 将本地图像而不是 URL 发送到计算机视觉 API

问题描述

我想上传本地图像文件并从中提取文本。我点击了下面的链接,当我传递 URL 时它按预期工作。https://docs.microsoft.com/en-us/azure/developer/javascript/tutorial/static-web-app/add-computer-vision-react-app

我设法为本地图像配置并获取上传图像的 base64 编码 dataURL。但是当我将 base64 编码的 dataURL 传递给 Computer Vision API 时,它会显示“输入数据不是有效图像”(POST 400 状态代码)。我在下面显示的行中遇到错误: const analysis = await computerVisionClient.analyzeImage(urlToAnalyze, { visualFeatures });

我包含的用于处理本地图像的代码:

 const handleChange = (e) => {
    var file = e.target.files[0];
    var reader = new FileReader();
    reader.onloadend = function()
    {
        setFileSelected(reader.result) // this is the base64 encoded dataurl
    }
   reader.readAsDataURL(file);
}

在computerVision.js 文件中,我更改了标题中的“contentType”,如下所示。

 const computerVisionClient = new ComputerVisionClient(
    new ApiKeyCredentials({ inHeader: {'Ocp-Apim-Subscription-Key': key, 'Content-Type': 'application/octet-stream'} }), endpoint);

我尝试根据 computerVision.js 中的文档将 client.read() 替换为 readTextInStream() (请参阅上面的链接),但仍然抛出错误。

我可以知道为什么我收到错误“输入数据不是有效图像”吗?谢谢。

标签: reactjsazurefile-uploadcomputer-visionocr

解决方案


这是输入要求的链接

微软提供了一个全新的在线门户https://preview.vision.azure.com/demo/OCR

好处是它会直接列出你可用的资源,所以你只需要选择合适的,然后你测试,还有一些样本。


推荐阅读