Optical Character Recognition

Text Analysis

Utilizing OCR.Space OCRAPI

OCR.Space OCRAPI is a public API that can be used for Optical Character Recognition. It helps to extract text from images and convert them into editable formats. Here we will learn how to use OCR.Space OCRAPI in our JavaScript project.

The API's endpoint URL is https://api.ocr.space/parse/image and requires an API key. Go to the OCR.Space OCRAPI website and sign up for an API key.

Installing Required Libraries

To utilize the OCRAPI, we need to install axios to send HTTP requests and FormData to parse the data. Both can be installed using npm.

npm install axios form-data

Uploading Data to OCRAPI

The OCRAPI needs a multipart/form-data format of the image file. For this, we use the FormData class in JavaScript. Let's create a function that uploads an image file to OCRAPI and returns the output.

async function ocrSpaceAPI(imgFile) {
    const apiUrl = 'https://api.ocr.space/parse/image'
    const apiKey = '<your_api_key_here>'
    const formData = new FormData()
    formData.append("file", imgFile)

    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        },
        data: formData
    }

    const { data } = await axios.post(apiUrl, config, {
        params: {
            'apikey': `${apiKey}`,
            'language': 'eng',
            'isOverlayRequired': 'false'
        }
    })
    return data
}

This function will take the image file as an argument and return the OCR output as JSON.

Utilizing the Output

Now that we have the JSON output, we need to extract the relevant information from it. Here's an example of extracting the text from a JSON output:

const imgFile = document.querySelector('#imgFile')
imgFile.addEventListener('change', async function() {
    const file = this.files[0]
    const ocrOutput = await ocrSpaceAPI(file)
    alert(ocrOutput.ParsedResults[0].ParsedText)
})

This code will create an event listener on the input element with an id of imgFile. When the file is changed, the OCRAPI will be called, and the extracted text will be displayed as an alert.

Conclusion

In conclusion, OCR.Space OCRAPI is a powerful tool to extract text from images. With this short guide, you should understand how to use the OCRAPI in your JavaScript project.

Related APIs