Mac Ventura下XAMPP运行Tesseract OCR报错求助
解决XAMPP中Tesseract OCR运行问题(Mac Ventura)
问题描述
在Mac Ventura中已安装Tesseract OCR,终端及/usr/local路径下的Apache2运行PHP代码正常,但XAMPP环境中出现两个核心问题:
- 初始报错:
Error! The command "tesseract" was not found.,当前PHP环境的$PATH仅包含/usr/bin:/bin:/usr/sbin:/sbin - 指定Tesseract执行路径后,触发PHP致命错误:
_WebPMalloc符号未找到,根源是系统/usr/local/Cellar/webp/1.3.2/lib/libwebpmux.3.0.13.dylib与XAMPP自带的/Applications/XAMPP/xamppfiles/lib/libwebp.7.dylib版本冲突
解决方案
1. 修复Tesseract命令找不到的问题
XAMPP的Apache进程运行时的环境变量PATH未包含Homebrew安装的Tesseract路径(通常为/usr/local/bin,M系列芯片为/opt/homebrew/bin),可通过两种方式解决:
方式一:在PHP代码中指定Tesseract完整路径
修改TesseractOCR初始化逻辑,添加->executable()方法指定执行文件路径:
$fileRead = (new TesseractOCR('uploads/' . $file_name)) ->executable('/usr/local/bin/tesseract') // M系列芯片替换为/opt/homebrew/bin/tesseract ->setLanguage('eng') ->run();
方式二:修改XAMPP的Apache环境变量
编辑XAMPP的Apache配置文件/Applications/XAMPP/xamppfiles/etc/httpd.conf,在文件末尾添加:
SetEnv PATH "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
M系列芯片用户需将/usr/local/bin替换为/opt/homebrew/bin,修改后重启XAMPP的Apache服务。
2. 解决WebP库冲突问题
XAMPP自带的旧版libwebp与Tesseract依赖的新版libwebpmux冲突,导致符号缺失,可通过设置环境变量让Tesseract优先加载系统库:
方式一:在PHP代码中临时设置环境变量
在执行Tesseract前,添加环境变量配置:
try { // 让Tesseract优先加载系统的webp库 putenv('DYLD_LIBRARY_PATH=/usr/local/Cellar/webp/1.3.2/lib:' . getenv('DYLD_LIBRARY_PATH')); $fileRead = (new TesseractOCR('uploads/' . $file_name)) ->executable('/usr/local/bin/tesseract') ->setLanguage('eng') ->run(); } catch (Exception $e) { echo $e->getMessage(); }
方式二:修改XAMPP启动脚本
编辑XAMPP启动脚本/Applications/XAMPP/xamppfiles/xampp,在启动Apache的代码段前添加:
export DYLD_LIBRARY_PATH="/usr/local/Cellar/webp/1.3.2/lib:$DYLD_LIBRARY_PATH"
若后续webp版本更新,需同步调整路径。修改后重启XAMPP服务即可。
注意事项
- 禁止直接替换XAMPP自带的libwebp库,可能导致PHP、Apache等组件运行异常
- 可通过终端执行
which tesseract和brew --prefix webp命令,确认Tesseract和webp的准确安装路径
完整修改后的PHP核心代码
$fileRead = ''; use thiagoalessio\TesseractOCR\TesseractOCR; require 'vendor/autoload.php'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (isset($_POST['submit'])) { $file_name = $_FILES['file']['name']; $tmp_file = $_FILES['file']['tmp_name']; if (!session_id()) { session_start(); $unq = session_id(); } $file_name = uniqid() . '_' . time() . '_' . str_replace(array('!', "@", '#', '$', '%', '^', '&', ' ', '*', '(', ')', ':', ';', ',', '?', '/' . '\\', '~', '`', '-'), '_', strtolower($file_name)); if (move_uploaded_file($tmp_file, 'uploads/' . $file_name)) { try { // 配置环境变量解决库冲突 putenv('DYLD_LIBRARY_PATH=/usr/local/Cellar/webp/1.3.2/lib:' . getenv('DYLD_LIBRARY_PATH')); $fileRead = (new TesseractOCR('uploads/' . $file_name)) ->executable('/usr/local/bin/tesseract') // M系列芯片替换为/opt/homebrew/bin/tesseract ->setLanguage('eng') ->run(); } catch (Exception $e) { echo $e->getMessage(); } } else { echo "<p class='alert alert-danger'>File failed to upload.</p>"; } } }
内容的提问来源于stack exchange,提问作者Yeezus
相关产品推荐
相关产品推荐

