当前位置: 首页 > 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.gsyq.cn/news/1458844.html

相关文章:

  • Grok-1本地部署构建自动素材池实战指南
  • 从安装到调参:一份超详细的imbalanced-learn库实战指南(附Jupyter Notebook代码)
  • 仓储软件(WMS)值得推荐的实用选择参考 - 品牌排行榜
  • 从收藏吃灰到高效执行:2026年度高内聚代码灵感仓储工具深度解析
  • 量子退火在最小顶点多割问题中的应用与优化
  • 工单响应时效从47分钟压缩至92秒,这3个AI集成节点你绝对漏掉了
  • 百度网盘限速终结者:3分钟搞定高速下载的终极方案
  • 用超声波传感器与Arduino制作自由形态电子秤:从测距到称重的跨界实践
  • PHP图数据结构与算法实现
  • Gemma 4 9B:面向开发者的轻量级AI生产力引擎
  • 动态多重网络层间差异检验:谱嵌入与Bootstrap方法
  • OpenCode 教程目录
  • 量子上三角矩阵代数UTq(n)的构造与Hopf结构解析
  • 公平k中心聚类算法:原理、优化与应用
  • 大模型能力演进:从版本幻觉到多模态原生表征
  • 避坑指南:STM32F103标准库DAC配置的那些“坑”与最佳实践
  • 利用快马内置git环境,三步完成项目原型创建与版本初始化
  • Gemini 3.0实战指南:多模态理解与长上下文推理落地方法论
  • 开发2天,测试2个月:AI代码让谁偷懒了?
  • ZYNQ Linux下UIO中断配置踩坑记:从/dev下找不到uio设备到按键触发成功
  • 效率飙升:快马AI为你自动生成CentOS7运维管理效率工具包
  • 手机号定位查询系统:3秒获取号码归属地与地理位置
  • 避坑指南:STM32 HAL库下TM1640时序调试的那些事儿(基于SysTick和定时器两种延时)
  • 十年教学经验总结:新手小提琴怎么选?全价位高口碑机型实测推荐
  • 别再让EMC测试卡脖子!硬件工程师必看的电磁兼容设计实战避坑指南
  • 大语言模型越狱攻击:原理、挑战与防御策略
  • 实战cnn项目:基于快马ai生成从数据加载到模型可视化的猫狗分类完整代码
  • 第一章:OpenCode 项目概览与核心定位
  • 2026论文降AI率平台:11款工具实测谁在“智能”谁在“智障”?
  • 效率倍增:基于快马生成openclaw可参数化的一键部署与配置模板