当前位置: 首页 > news >正文

PHP图像识别与QR码生成技术

PHP图像识别与QR码生成技术

PHP可以通过GD库和第三方库处理图像,生成二维码和条形码。今天说说PHP中的图像识别和二维码生成。

QR码生成可以用endroid/qr-code库,纯PHP实现不需要外部依赖。

```php
require 'vendor/autoload.php';

use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Writer\SvgWriter;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;

function generateQrCode(string $data, string $outputPath = '/tmp/qrcode.png', int $size = 300): void
{
$qrCode = QrCode::create($data)
->setEncoding(new Encoding('UTF-8'))
->setErrorCorrectionLevel(ErrorCorrectionLevel::Medium)
->setSize($size)
->setMargin(10);

$writer = new PngWriter();
$result = $writer->write($qrCode);
$result->saveToFile($outputPath);

echo "QR码已生成: {$outputPath}\n";
}

function generateQrCodeSvg(string $data): string
{
$qrCode = QrCode::create($data)
->setEncoding(new Encoding('UTF-8'))
->setErrorCorrectionLevel(ErrorCorrectionLevel::Low)
->setSize(200)
->setMargin(10);

$writer = new SvgWriter();
$result = $writer->write($qrCode);
return $result->getString();
}

generateQrCode('https://example.com', '/tmp/qrcode.png');
$svg = generateQrCodeSvg('https://example.com');
echo "SVG QR码长度: " . strlen($svg) . " 字符\n";
?>
```

用GD库生成条形码:

```php
class BarcodeGenerator
{
public function generateCode128(string $text, int $width = 400, int $height = 100): string
{
$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);

imagefill($image, 0, 0, $white);

// 简化条码生成(仅示例)
$bars = $this->encodeText($text);
$x = 10;
$barWidth = ($width - 20) / count($bars);

foreach ($bars as $bar) {
if ($bar === 1) {
imagefilledrectangle($image, (int)$x, 5, (int)($x + $barWidth), $height - 20, $black);
}
$x += $barWidth;
}

// 添加文字
$textColor = imagecolorallocate($image, 0, 0, 0);
$textWidth = strlen($text) * imagefontwidth(3);
$textX = ($width - $textWidth) / 2;
imagestring($image, 3, (int)$textX, $height - 15, $text, $textColor);

ob_start();
imagepng($image);
$imageData = ob_get_clean();
imagedestroy($image);

return base64_encode($imageData);
}

private function encodeText(string $text): array
{
// 简化的编码
$bits = [];
foreach (str_split($text) as $char) {
$byte = ord($char);
for ($i = 7; $i >= 0; $i--) {
$bits[] = ($byte >> $i) & 1;
}
}
return $bits;
}
}

$barcode = new BarcodeGenerator();
echo "

\n";
?>
```

图像基本处理用GD库就够了:

```php
class ImageProcessor
{
public function resize(string $sourcePath, string $destPath, int $maxWidth, int $maxHeight): void
{
$info = getimagesize($sourcePath);
if ($info === false) {
throw new RuntimeException("无法读取图像");
}

[$origWidth, $origHeight, $type] = $info;

$ratio = min($maxWidth / $origWidth, $maxHeight / $origHeight);
$newWidth = (int)($origWidth * $ratio);
$newHeight = (int)($origHeight * $ratio);

$sourceImage = match ($type) {
IMAGETYPE_JPEG => imagecreatefromjpeg($sourcePath),
IMAGETYPE_PNG => imagecreatefrompng($sourcePath),
IMAGETYPE_GIF => imagecreatefromgif($sourcePath),
IMAGETYPE_WEBP => imagecreatefromwebp($sourcePath),
default => throw new RuntimeException("不支持的图片类型"),
};

$destImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);

match ($type) {
IMAGETYPE_JPEG => imagejpeg($destImage, $destPath, 85),
IMAGETYPE_PNG => imagepng($destImage, $destPath, 9),
IMAGETYPE_GIF => imagegif($destImage, $destPath),
IMAGETYPE_WEBP => imagewebp($destImage, $destPath, 85),
};

imagedestroy($sourceImage);
imagedestroy($destImage);
}

public function addWatermark(string $sourcePath, string $destPath, string $watermarkText): void
{
$image = imagecreatefromjpeg($sourcePath);
$width = imagesx($image);
$height = imagesy($image);

$textColor = imagecolorallocatealpha($image, 255, 255, 255, 80);
$fontSize = 20;

$fontFile = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf';
if (file_exists($fontFile)) {
$textBox = imagettfbbox($fontSize, 0, $fontFile, $watermarkText);
$textWidth = $textBox[2] - $textBox[0];
$x = $width - $textWidth - 20;
$y = $height - 20;
imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontFile, $watermarkText);
} else {
$x = $width - (strlen($watermarkText) * imagefontwidth(5)) - 10;
$y = $height - 30;
imagestring($image, 5, $x, $y, $watermarkText, $textColor);
}

imagejpeg($image, $destPath, 90);
imagedestroy($image);
}

public function createThumbnailFromBase64(string $base64, int $maxSize = 200): string
{
$data = base64_decode($base64);
$image = imagecreatefromstring($data);
$width = imagesx($image);
$height = imagesy($image);

$ratio = min($maxSize / $width, $maxSize / $height);
$newWidth = (int)($width * $ratio);
$newHeight = (int)($height * $ratio);

$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

ob_start();
imagejpeg($thumb, null, 80);
$thumbData = ob_get_clean();
imagedestroy($image);
imagedestroy($thumb);

return base64_encode($thumbData);
}
}
?>
```

PHP的图像处理能力虽然不如专业工具,但生成二维码、条形码、图片缩放和水印这些常见需求都能满足。对于复杂的图像识别,建议使用专业的OCR或计算机视觉服务。

http://www.jsqmd.com/news/947332/

相关文章:

  • 语义内核形式化模型:AI内容生成的统一数学原理与工程实践
  • Grok-1本地部署构建自动素材池实战指南
  • 仓储软件(WMS)值得推荐的实用选择参考 - 品牌排行榜
  • 从安装到调参:一份超详细的imbalanced-learn库实战指南(附Jupyter Notebook代码)
  • 深耕车载数字健康场景,守护全维度驾乘安全与体验
  • 小程序毕业设计-基于ssm电影院网上订票系统的设计与实现小程序基于Android的电影院网上订票系统(源码+LW+部署文档+全bao+远程调试+代码讲解等)
  • GBase 8s数据库高可用之—RHAC远程高可用集群详解
  • PHP图形验证码技术实现
  • 从收藏吃灰到高效执行:2026年度高内聚代码灵感仓储工具深度解析
  • 第七章:自定义命令、规则与上下文
  • 别慌!网站突然打不开显示Error 522?手把手教你排查百度云加速与源站的连接问题
  • DeepSeek V4实测:百万上下文与MoE架构如何重构AI成本模型
  • 量子退火在最小顶点多割问题中的应用与优化
  • 仓储软件(WMS)值得推荐的选择方向 - 品牌排行榜
  • 第八章:工具、权限与 MCP 扩展
  • 用超声波传感器与Arduino制作自由形态电子秤:从测距到称重的跨界实践
  • 如何快速定位手机号码归属地:三步完成精准查询
  • AI工具链×秒杀核心链路深度耦合实践(阿里/拼多多/得物三巨头架构师联合复盘版)
  • PHP图数据结构与算法实现
  • 工单响应时效从47分钟压缩至92秒,这3个AI集成节点你绝对漏掉了
  • 利用快马平台快速构建potplayer字幕翻译工具原型
  • 百度网盘限速终结者:3分钟搞定高速下载的终极方案
  • 合规红线下的智能外呼:如何用RAG+本地化语音模型通过银保监AI外呼备案(附过审配置清单)
  • 伺服驱动器方向反转排查与设置
  • Gemma 4 9B:面向开发者的轻量级AI生产力引擎
  • 动态多重网络层间差异检验:谱嵌入与Bootstrap方法
  • OpenCode 教程目录
  • Determined:一个集成的深度学习训练平台
  • 计算机重装系统出现SYSTEM磁盘?
  • 量子上三角矩阵代数UTq(n)的构造与Hopf结构解析