javascripthtmltesseract.js

How to convert from image to text using Javascript


I am trying to convert image to text. When anyone upload image then press "Submit" image text should be show into the textarea. My following code is not working, please help!

Code:

 <html>
    <body>
    
    <input type="file" id="myFile" name="filename">  
    <br><br>
<button onclick="myFunction()">Submit</button>
<br><br>
    
    <label><b>Your Converted Text:</b></label><br><br>
    
    <textarea cols="30" name="original" rows="10" style="width: 100%;" id="convertedText">
    </textarea>

    <script src='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'></script>
    
    <script>  
     function myFunction() {
           var myImage= document.getElementById('myFile');
          
    
           Tesseract.recognize(myImage).then(function(result){
    
            console.log(result.text);
    
           document.getElementById("convertedText").value = result.text;
            
    
            });
    }
            </script>
            
    </body>
    </html>

Solution

  • If you attach an event listener to the file input, you can then recognize text once the file has been loaded successfully, like so:

    <html>
    <body>
    
    <input type="file" id="myFile" name="filename">  
    <br><br>
    
    <label><b>Your Converted Text:</b></label><br><br>
    
    <textarea cols="30" name="original" rows="10" style="width: 100%;" id="convertedText">
    </textarea>
    
    <script src='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'></script>
    
    <script>  
    
        var myFile = document.getElementById('myFile');
        myFile.addEventListener('change', recognizeText);
    
        async function recognizeText({ target: { files }  }) {
            Tesseract.recognize(files[0]).then(function(result) {
                console.log("recognizeText: result.text:", result.text);
                document.getElementById("convertedText").value = result.text;
            });
        }
    
    </script>
            
    </body>
    </html>