news 2026/6/4 7:34:59

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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或计算机视觉服务。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/4 7:32:55

解锁抖音内容管理:开源工具的高效解决方案实战指南

解锁抖音内容管理:开源工具的高效解决方案实战指南 【免费下载链接】douyin-downloader A practical Douyin downloader for both single-item and profile batch downloads, with progress display, retries, SQLite deduplication, and browser fallback support.…

作者头像 李华
网站建设 2026/6/4 7:22:42

蜘蛛池技术解析:原理、作用与作用点评——专业视角下的网站录入

本文体系论说了蜘蛛池技术的中心原理、运作机制及其在搜索引擎优化(SEO)中的实践运用价值。通过剖析蜘蛛池对搜索引擎爬虫的引导作用,探讨了其在行进网站录入率、加快页面抓取方面的技术优势。一起,本文客观点评了蜘蛛池技术的运用作用,并提出…

作者头像 李华
网站建设 2026/6/4 7:22:04

智能决策系统上线失败真相(2024最新Gartner数据验证)

更多请点击: https://kaifayun.com 第一章:智能决策系统上线失败真相(2024最新Gartner数据验证) 根据Gartner 2024年7月发布的《AI in Production: Failure Root-Cause Analysis》报告,全球企业部署的智能决策系统中&…

作者头像 李华
网站建设 2026/6/4 7:17:55

电子厂用什么管理软件?珠三角中小电子厂主流选择:专业易特电子行业ERP深度测评

标签:电子厂管理 ERP系统 工厂数字化 珠三角制造业 生产管理软件在珠三角东莞、深圳、佛山、惠州这片电子制造产业高地,大大小小的SMT贴片厂、线束加工厂、小家电电子厂、元器件组装厂数不胜数。绝大多数中小电子厂都面临一模一样的管理难题:…

作者头像 李华