本文目录导读:

我将为您详细介绍如何在PHP项目中集成OCR文字识别功能,以下是几种主流方案的实现方法:
使用第三方云服务API(推荐)
百度智能云OCR
<?php
class BaiduOCR {
private $apiKey;
private $secretKey;
private $accessToken;
public function __construct($apiKey, $secretKey) {
$this->apiKey = $apiKey;
$this->secretKey = $secretKey;
$this->getAccessToken();
}
// 获取访问令牌
private function getAccessToken() {
$url = 'https://aip.baidubce.com/oauth/2.0/token';
$postData = [
'grant_type' => 'client_credentials',
'client_id' => $this->apiKey,
'client_secret' => $this->secretKey
];
$result = $this->httpRequest($url, $postData);
$this->accessToken = $result['access_token'];
}
// 通用文字识别(含位置高精版)
public function generalOCR($imagePath) {
$url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={$this->accessToken}";
$image = base64_encode(file_get_contents($imagePath));
$postData = ['image' => $image];
$result = $this->httpRequest($url, $postData);
return $result;
}
// 身份证识别
public function idCardOCR($imagePath, $side = 'front') {
$url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={$this->accessToken}";
$image = base64_encode(file_get_contents($imagePath));
$postData = [
'image' => $image,
'id_card_side' => $side
];
$result = $this->httpRequest($url, $postData);
return $result;
}
// HTTP请求封装
private function httpRequest($url, $postData) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
// 使用示例
$ocr = new BaiduOCR('你的API_KEY', '你的SECRET_KEY');
$result = $ocr->generalOCR('test.jpg');
if (isset($result['words_result'])) {
foreach ($result['words_result'] as $item) {
echo $item['words'] . "\n";
}
}
?>
腾讯云OCR
<?php
class TencentOCR {
private $secretId;
private $secretKey;
public function __construct($secretId, $secretKey) {
$this->secretId = $secretId;
$this->secretKey = $secretKey;
}
public function generalOCR($imagePath) {
// 腾讯云OCR接口
$host = "ocr.tencentcloudapi.com";
$action = "GeneralBasicOCR";
$timestamp = time();
$date = gmdate('Y-m-d', $timestamp);
// 生成签名
$signature = $this->generateSignature($action, $timestamp, $date);
$image = base64_encode(file_get_contents($imagePath));
$postData = [
'ImageBase64' => $image
];
$headers = [
'Authorization: TC3-HMAC-SHA256 Credential=' . $this->secretId . '/' . $date . '/ocr/tc3_request',
'Content-Type: application/json',
'X-TC-Action: ' . $action,
'X-TC-Timestamp: ' . $timestamp,
'X-TC-Version: 2018-11-19',
'X-TC-Region: ap-guangzhou',
'X-TC-Token: ' . $signature
];
return $this->httpRequest($host, $postData, $headers);
}
private function generateSignature($action, $timestamp, $date) {
// 实现签名逻辑(简化版)
return hash_hmac('sha256', $action . $timestamp, $this->secretKey);
}
private function httpRequest($host, $postData, $headers) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://" . $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
?>
使用Tesseract OCR(开源免费)
安装配置
# Ubuntu/Debian sudo apt-get install tesseract-ocr sudo apt-get install tesseract-ocr-chi-sim # 中文简体语言包 # CentOS/RHEL sudo yum install tesseract sudo yum install tesseract-langpack-chi-sim
PHP集成
<?php
class TesseractOCR {
private $executablePath;
private $language;
public function __construct($executablePath = '/usr/bin/tesseract', $language = 'chi_sim+eng') {
$this->executablePath = $executablePath;
$this->language = $language;
}
public function recognize($imagePath) {
// 生成临时输出文件
$outputPath = tempnam(sys_get_temp_dir(), 'ocr');
// 构建命令
$command = sprintf(
'%s "%s" "%s" -l %s 2>&1',
escapeshellcmd($this->executablePath),
escapeshellarg($imagePath),
escapeshellarg($outputPath),
escapeshellarg($this->language)
);
// 执行命令
exec($command, $output, $returnCode);
if ($returnCode !== 0) {
throw new Exception("OCR识别失败: " . implode("\n", $output));
}
// 读取结果
$text = file_get_contents($outputPath . '.txt');
// 清理临时文件
unlink($outputPath);
return $text;
}
// 高级:支持图像预处理
public function recognizeWithPreprocessing($imagePath) {
// 使用GD2库进行图像预处理
$imageInfo = getimagesize($imagePath);
$mimeType = $imageInfo['mime'];
// 根据图像类型创建图像资源
switch ($mimeType) {
case 'image/jpeg':
$image = imagecreatefromjpeg($imagePath);
break;
case 'image/png':
$image = imagecreatefrompng($imagePath);
break;
case 'image/gif':
$image = imagecreatefromgif($imagePath);
break;
default:
throw new Exception("不支持的图像格式");
}
// 灰度化处理
imagefilter($image, IMG_FILTER_GRAYSCALE);
// 增强对比度
imagefilter($image, IMG_FILTER_CONTRAST, -5);
// 反转颜色(黑底白字)
imagefilter($image, IMG_FILTER_NEGATE);
// 保存预处理后的图像
$tempFile = tempnam(sys_get_temp_dir(), 'pre');
imagejpeg($image, $tempFile, 90);
// 释放内存
imagedestroy($image);
// 执行OCR
$result = $this->recognize($tempFile);
// 清理临时文件
unlink($tempFile);
return $result;
}
}
// 使用示例
$ocr = new TesseractOCR('/usr/bin/tesseract', 'chi_sim+eng');
$text = $ocr->recognize('document.jpg');
echo $text;
?>
使用PHP扩展库
安装 EasyOCR PHP库
composer require anourvalar/php-easyocr
使用示例
<?php
require_once 'vendor/autoload.php';
use AnourValar\PhpEasyOcr\Provider\TesseractProvider;
use AnourValar\PhpEasyOcr\OcrClient;
class EasyOCRWrapper {
private $client;
public function __construct() {
$this->client = new OcrClient();
$provider = new TesseractProvider();
$provider->setTesseractPath('/usr/bin/tesseract');
$provider->setLanguage('chi_sim');
$provider->setPsm(3);
$this->client->addProvider($provider);
}
public function recognize($imagePath) {
return $this->client->detect($imagePath);
}
}
// 使用示例
$ocr = new EasyOCRWrapper();
$result = $ocr->recognize('test.png');
var_dump($result);
?>
完整的上传文件OCR识别示例
<?php
class OCRController {
private $ocr;
private $uploadDir;
public function __construct($ocr, $uploadDir = './uploads/') {
$this->ocr = $ocr;
$this->uploadDir = $uploadDir;
// 创建上传目录
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
}
// 处理上传的图片并进行OCR识别
public function processUpload($files) {
if (!isset($files['file']) || $files['file']['error'] !== UPLOAD_ERR_OK) {
throw new Exception("文件上传失败");
}
$file = $files['file'];
$filePath = $this->uploadFile($file);
try {
// 执行OCR识别
$result = $this->ocr->recognize($filePath);
// 清理临时文件
unlink($filePath);
return $result;
} catch (Exception $e) {
if (file_exists($filePath)) {
unlink($filePath);
}
throw $e;
}
}
// 上传文件
private function uploadFile($file) {
// 验证文件类型
$allowedTypes = ['image/jpeg', 'image/png', 'image/bmp', 'image/gif'];
if (!in_array($file['type'], $allowedTypes)) {
throw new Exception("不支持的文件类型");
}
// 验证文件大小(5MB限制)
if ($file['size'] > 5 * 1024 * 1024) {
throw new Exception("文件大小超过限制");
}
// 生成唯一文件名
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '.' . $ext;
$filePath = $this->uploadDir . $filename;
// 移动文件
if (!move_uploaded_file($file['tmp_name'], $filePath)) {
throw new Exception("文件保存失败");
}
return $filePath;
}
}
// 使用示例 - 上传处理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
// 选择OCR方案
$ocr = new BaiduOCR('API_KEY', 'SECRET_KEY');
// 或 $ocr = new TesseractOCR('/usr/bin/tesseract', 'chi_sim');
$controller = new OCRController($ocr);
$result = $controller->processUpload($_FILES);
// 输出结果
echo json_encode([
'success' => true,
'text' => $result
]);
} catch (Exception $e) {
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}
}
?>
前端HTML表单示例
<!DOCTYPE html>
<html>
<head>OCR 文字识别</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 20px auto;
padding: 20px;
}
.upload-form {
border: 2px dashed #ddd;
padding: 20px;
text-align: center;
}
#result {
margin-top: 20px;
padding: 20px;
border: 1px solid #ccc;
}
.btn {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>文档OCR识别</h2>
<form class="upload-form" id="ocrForm">
<input type="file" id="image" name="file" accept="image/*" required>
<br><br>
<button type="submit" class="btn">开始识别</button>
</form>
<div id="result"></div>
<script>
document.getElementById('ocrForm').addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData();
formData.append('file', document.getElementById('image').files[0]);
try {
const response = await fetch('/ocr.php', {
method: 'POST',
body: formData
});
const data = await response.json();
const resultDiv = document.getElementById('result');
if (data.success) {
resultDiv.innerHTML = '<h3>识别结果:</h3><pre>' + data.text + '</pre>';
} else {
resultDiv.innerHTML = '<div style="color: red;">错误:' + data.error + '</div>';
}
} catch (error) {
alert('服务器错误:' + error.message);
}
});
</script>
</body>
</html>
使用建议
-
云服务方案:
- 准确率高,支持多种语言
- 简单易用,无需本地安装和库文件
- 按量计费,适合商业项目
-
开源方案(Tesseract):
- 免费使用,成本低
- 可以离线运行
- 需要安装依赖和训练数据
-
性能优化:
- 对于大批量处理,建议使用队列系统
- 图片上传后先压缩再处理
- 合理使用缓存,减少重复调用
-
安全性:
- 对上传文件进行严格验证
- 使用HTTPS传输
- 保护API密钥,不要暴露在前端
根据您的具体需求和预算,选择合适的OCR方案,如果需要更详细的实现细节,请告诉我。