当前位置:首页 > PHP

php 实现 ocr

2026-01-30 04:49:16PHP

PHP 实现 OCR 的方法

PHP 可以通过集成第三方 OCR 库或 API 实现文本识别功能。以下是几种常见的方法:

使用 Tesseract OCR

Tesseract 是一个开源的 OCR 引擎,支持多种语言。可以通过 PHP 调用 Tesseract 命令行工具或使用包装库。

安装 Tesseract:

sudo apt install tesseract-ocr
sudo apt install libtesseract-dev

通过 PHP 调用 Tesseract:

$imagePath = 'path/to/image.png';
$outputPath = 'path/to/output.txt';

// 执行 Tesseract 命令
exec("tesseract $imagePath $outputPath");

// 读取识别结果
$text = file_get_contents($outputPath . '.txt');
echo $text;

使用 thiagoalessio/tesseract_ocr 包装库:

php 实现 ocr

require 'vendor/autoload.php';
use thiagoalessio\TesseractOCR\TesseractOCR;

echo (new TesseractOCR('path/to/image.png'))
    ->lang('eng')
    ->run();

调用云 OCR API

许多云服务提供 OCR 功能,如 Google Cloud Vision、Azure Computer Vision 或百度 OCR。

Google Cloud Vision 示例:

require 'vendor/autoload.php';
use Google\Cloud\Vision\VisionClient;

$vision = new VisionClient([
    'keyFilePath' => 'path/to/service-account.json'
]);

$image = $vision->image(file_get_contents('path/to/image.png'), ['TEXT_DETECTION']);
$result = $vision->annotate($image);

foreach ($result->text() as $text) {
    echo $text->description() . PHP_EOL;
}

百度 OCR 示例:

php 实现 ocr

$image = file_get_contents('path/to/image.png');
$base64 = base64_encode($image);

$url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=YOUR_ACCESS_TOKEN";
$data = ['image' => $base64];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
print_r($result['words_result']);

使用本地 PHP OCR 库

php-ocr 是一个纯 PHP 实现的 OCR 库,适合简单需求。

安装:

composer require smalot/pdfparser

示例代码:

require 'vendor/autoload.php';
use Smalot\PdfParser\Parser;

$parser = new Parser();
$pdf = $parser->parseFile('path/to/document.pdf');
$text = $pdf->getText();
echo $text;

注意事项

  • Tesseract 对图像质量要求较高,预处理(如二值化、降噪)能提升识别率。
  • 云 API 通常有调用限制和费用,需注册并获取 API Key。
  • 本地库适合轻量需求,复杂场景建议使用 Tesseract 或云服务。

标签: phpocr
分享给朋友:

相关文章

php实现文件的下载

php实现文件的下载

PHP 实现文件下载的方法 在 PHP 中实现文件下载功能通常需要设置正确的 HTTP 头信息,并输出文件内容。以下是几种常见的实现方式: 使用 header() 函数强制下载 通过设置 Conte…

php实现一个

php实现一个

PHP 实现一个简单的计算器 创建一个基本的计算器,支持加、减、乘、除运算。以下是一个完整的实现代码示例: <?php $result = ""; if ($_SERVER["REQUEST_…

php 实现跳转

php 实现跳转

PHP 实现页面跳转的方法 在PHP中,实现页面跳转可以通过多种方式完成,以下是几种常用的方法: 使用header函数 header函数是PHP中最常用的跳转方法,通过发送HTTP头部信息实现跳转。…

php实现推送消息推送消息

php实现推送消息推送消息

PHP 实现消息推送的方法 使用 WebSocket 实现实时推送 WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,适合实现实时消息推送。 安装 Ratchet 库(WebSo…

php实现异步图片上传

php实现异步图片上传

异步图片上传的实现方法 在PHP中实现异步图片上传通常需要结合前端JavaScript和后端PHP代码。以下是几种常见的方法: 使用XMLHttpRequest或Fetch API 前端使用Java…

php实现单一入口

php实现单一入口

PHP 单一入口实现方法 单一入口(Single Entry Point)是一种设计模式,通过一个入口文件(如index.php)集中处理所有请求,实现路由分发、统一初始化等操作。以下是实现方法:…