效果:1:
效果图2:

一、安装tesseract.js
复制
二、静态页面实现
| <template> |
| <div> |
| <div style="marginTop:100px"> |
| <input @change="handleChage" type="file" id="image-input" accept="image/*"> |
| <br /> |
| <button @click="processImage">提取文字</button> |
| <div id="show-picture"></div> |
| </div> |
| <div> |
| <p style="color:red">提取到的内容:</p> |
| <span id="result"></span> |
| </div> |
| </div> |
| </template> |
复制

三、选择图片显示在页面上
| <script setup> |
| |
| import { createWorker } from 'tesseract.js'; |
| |
| |
| |
| const handleChage = () => { |
| |
| document.getElementById("result").innerText = "" |
| let getUserPhoto = document.getElementById("image-input"); |
| |
| |
| |
| let reader = new FileReader(); |
| |
| |
| reader.readAsDataURL(getUserPhoto.files[0]); |
| |
| |
| reader.onload = function () { |
| let image = document.createElement("img"); |
| image.width = "400"; |
| |
| |
| image.src = reader.result; |
| let showPicture = document.getElementById("show-picture"); |
| while (showPicture.firstChild) { |
| showPicture.removeChild(showPicture.firstChild); |
| } |
| showPicture.appendChild(image) |
| }; |
| } |
| |
| <script> |
复制
四、核心代码,功能实现
| const processImage = () => { |
| let worker; |
| let input = document.getElementById('image-input'); |
| if (input.files && input.files[0]) { |
| let reader = new FileReader(); |
| reader.onload = async function (e) { |
| |
| |
| worker = await createWorker('chi_sim') |
| worker.recognize(e.target.result) |
| .then(result => { |
| |
| |
| let extractedText = result.data.text; |
| document.getElementById('result').innerText = extractedText; |
| |
| }) |
| .catch(error => { |
| console.error('Error:', error); |
| }).finally(() => { |
| if (worker) |
| |
| |
| worker.terminate(); |
| |
| }) |
| }; |
| reader.readAsDataURL(input.files[0]); |
| } |
| } |
复制
五、注:只能识别标准文本图片,并且会有误差,识别别的的图片效果会差很多

