DEV Community

Cover image for Implement OCR with React#2
honorezemagho
honorezemagho

Posted on • Updated on

Implement OCR with React#2

In the last tutorial we have implemented the upload functionality.
In this tutorial we are going to add Tesseract.js.

This article is divided in two parts. This is the part 2 , for the Part1 click here

Requirements

  • Nodejs version 8.10 or Higher.

First, we are going to install Tesseract.js package

npm install tesseract.js
Enter fullscreen mode Exit fullscreen mode

After we are going to import createWorker function it in src/App.js file .

import {createWorker} from "tesseract.js";
Enter fullscreen mode Exit fullscreen mode

inside the function App() we are going to add a worker and a method to recognize text inside an image.

  const worker = createWorker({
    logger: (m) => console.log(m),
});

const ExtractTextFromImage = async (imageUrl) => {
  await worker.load();
  await worker.loadLanguage("eng");
  await worker.initialize("eng");
  const {
      data: {
          text
      },
  } = await worker.recognize(imageUrl);
  setText(text);
  await worker.terminate();
};
Enter fullscreen mode Exit fullscreen mode

After we are going to define the state for image URL and text display. we are going to use useState and useEffect React Hook. First of all, we need to import useState from react.

 import React,{useEffect,useState} from "react";
Enter fullscreen mode Exit fullscreen mode

After

 const [ text, setText] = useState(null);

 const [imageUrl] = useState(null);

 useEffect(() => {
        if (imageUrl != null) {
            ExtractTextFromImage();
        }
    });
Enter fullscreen mode Exit fullscreen mode

Now we are going to add a container to display the text from the image in React.Fragment bloc.

  <div className = "container text-center pt-5" >
          {text}
  </div> 
Enter fullscreen mode Exit fullscreen mode

and update the text when processing the image.

const handleChangeStatus = ({
    meta
}, status) => {
    if (status === 'headers_received') {
      alert("Uploaded");
      setText("Recognizing...");
ExtractTextFromImage(meta.url);
    } else if (status === 'aborted') {
      alert("Something went wrong")
    }
}
Enter fullscreen mode Exit fullscreen mode

For the GitHub repository click Here

This article is divided into two parts. This is the part 2 , for the Part1 click here

Top comments (0)