Send local image to Computer Vision API using React

Sarah 161 Reputation points
2021-10-18T12:29:48.527+00:00

I would like to upload local image file and extract text from it. I followed the below link and it works as expected when I pass URL. https://learn.microsoft.com/en-us/azure/developer/javascript/tutorial/static-web-app/add-computer-vision-react-app

I managed to configure for local image and get the base64 encoded dataURL of the uploaded image. But when I pass base64 encoded dataURL to Computer Vision API , it says "Input data is not a valid image" (POST 400 status code). I am getting error in the line that is shown below:
const analysis = await computerVisionClient.analyzeImage(urlToAnalyze, { visualFeatures });

The code I have included for handling local image:

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);
}

In computerVision.js file, I have changed the 'contentType' in header as below.

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

I tried replacing client.read() with readTextInStream() as per docs in computerVision.js (please refer above link), but still throws error.

May I know why I get the error "Input data is not a valid image" ? Thanks.

Azure Computer Vision
Azure Computer Vision
An Azure artificial intelligence service that analyzes content in images and video.
311 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jianhua Wu 1 Reputation point
    2021-10-27T10:00:39.96+00:00

    for local image, please try the bellow:

            var fullpath = path.join(__dirname,filename) ;
            try{
                var result = await client.readInStream(() =>
                createReadStream(fullpath)
              );
            }catch(err){
                console.log(err);
            }
    
    0 comments No comments