如何使用 Javascript 从图像转换为文本

我正在尝试将图像转换为文本。当任何人上传图片然后按“提交”时,图片文本应该显示在文本区域中。我的以下代码不起作用,请帮助!


代码:


 <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>


慕娘9325324
浏览 230回答 1
1回答

慕森卡

如果将事件侦听器附加到文件输入,则可以在文件成功加载后识别文本,如下所示:<html><body><input type="file" id="myFile" name="filename">&nbsp;&nbsp;<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>&nbsp;&nbsp;&nbsp; &nbsp; var myFile = document.getElementById('myFile');&nbsp; &nbsp; myFile.addEventListener('change', recognizeText);&nbsp; &nbsp; async function recognizeText({ target: { files }&nbsp; }) {&nbsp; &nbsp; &nbsp; &nbsp; Tesseract.recognize(files[0]).then(function(result) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("recognizeText: result.text:", result.text);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("convertedText").value = result.text;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }</script>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript