在 PHP 中集成 Tesseract OCR 识别图片文字,核心做法是调用系统已安装的 tesseract 命令行工具。通过 exec() 或 proc_open() 执行命令,传入图片路径和输出目录,即可获取识别文本。

环境准备与基础调用
确保服务器已安装 Tesseract OCR 引擎及中文语言包(chi_sim)。使用 exec() 函数执行命令是最直接的方式,适用于大多数 Linux 环境。

执行命令时,需指定输入图片路径和输出文件前缀。Tesseract 默认将结果写入同名的 .txt 文件中。若需实时获取结果,可结合 proc_open() 读取标准输出流,避免频繁读写磁盘文件。
完整识别程序示例
以下代码展示了如何封装一个可靠的 OCR 识别类,包含错误处理、日志记录及多语言支持。请将此代码保存为 OcrService.php,并在项目中引入。

<?php
class OcrService
{
private $tesseractPath;
private $lang;
public function __construct($tesseractPath = '/usr/bin/tesseract', $lang = 'chi_sim+eng')
{
$this->tesseractPath = $tesseractPath;
$this->lang = $lang;
}
public function recognize($imagePath, $outputPrefix = 'output')
{
if (!file_exists($imagePath)) {
throw new Exception("Image file not found: {$imagePath}");
}
$cmd = sprintf(
'%s "%s" "%s" -l %s --oem 1 --psm 3',
escapeshellarg($this->tesseractPath),
$imagePath,
escapeshellarg($outputPrefix),
escapeshellarg($this->lang)
);
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w']
];
$process = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($process)) {
throw new Exception('Failed to start Tesseract process');
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
if ($stderr) {
error_log("Tesseract Warning: {$stderr}");
}
return trim($stdout);
}
}
// 使用示例
try {
$ocr = new OcrService();
$text = $ocr->recognize('test.jpg');
echo "Recognized Text: " . $text;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
程序运行成功后,控制台将输出识别到的纯文本内容。若图片路径错误或权限不足,会抛出异常并提示具体原因。对于复杂排版,调整 --psm 参数可改变页面分析模式,例如设为 6 表示假设统一大小的文本块。
该实现优先使用 proc_open() 以捕获 stderr 中的警告信息,便于排查图片格式不支持或语言包缺失等问题。运行后会在当前目录生成 output.txt 文件,内容为识别到的文字。
处理模糊图片的优化策略
当图片存在噪点或对比度低时,直接识别会导致准确率大幅下降。建议在调用 Tesseract 前,使用 GD 库对图片进行二值化处理,提升文字边缘清晰度。
二值化阈值通常设为 128 至 160 之间,具体取决于原图亮度。处理后保存图片再传入 Tesseract,可显著减少乱码。可通过设置环境变量 Tessdata_dir 指定语言包路径,避免版本冲突。