本文介绍了在 PHP 框架中集成一维码生成功能的方法。首先通过 Composer 安装 picqer/php-barcode-generator 三方类库,然后在 common/library 下封装 Barcode 类,提供获取 PNG 流、直接输出图片和保存到本地文件三种方法,最后在其他类中调用即可生成一维码。
目录
安装三方类库
命令
bash
composer require picqer/php-barcode-generator:2.2.0
安装完成,版本为2.4

封装类库
在common/library下创建Barcode.php,以备框架中调用,
内容如下:
php
<?php
require 'vendor/autoload.php';
use Picqer\Barcode\BarcodeGeneratorPNG;
use Picqer\Barcode\BarcodeGenerator;
class Barcode
{
/**
* 一维码类型常量映射,外部直接调用
*/
const CODE_128 = BarcodeGenerator::TYPE_CODE_128;
const EAN_13 = BarcodeGenerator::TYPE_EAN_13;
const CODE_39 = BarcodeGenerator::TYPE_CODE_39;
const UPC_A = BarcodeGenerator::TYPE_UPC_A;
/**
* 获取一维码PNG二进制流
* @param string $code 条码内容
* @param string $type 条码类型 BarcodeHelper::CODE_128
* @param int $widthFactor 单条宽度
* @param int $height 条码高度
* @param array $color 条码颜色 [R,G,B]
* @return string PNG图片二进制
*/
public static function getBarcodeStream(
string $code,
string $type = self::CODE_128,
int $widthFactor = 2,
int $height = 90,
array $color = [0, 0, 0]
): string {
$generator = new BarcodeGeneratorPNG();
// 强制使用GD库,避免imagick缺失报错(phpstudy默认只有gd)
$generator->useGd();
return $generator->getBarcode($code, $type, $widthFactor, $height, $color);
}
/**
* 直接输出图片到浏览器(接口使用)
* @param string $code
* @param string $type
* @return void
*/
public static function outputBarcode(
string $code,
string $type = self::CODE_128
): void {
$stream = self::getBarcodeStream($code, $type);
header('Content-Type:image/png');
echo $stream;
exit;
}
/**
* 保存条码到服务器本地文件
* @param string $code 条码内容
* @param string $savePath 保存完整路径 ./storage/barcode/xxx.png
* @param string $type
* @return bool
*/
public static function saveBarcode(
string $code,
string $savePath,
string $type = self::CODE_128
): bool {
$stream = self::getBarcodeStream($code, $type);
// 自动创建目录
$dir = dirname($savePath);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
return file_put_contents($savePath, $stream) !== false;
}
}
调用
在其他类中调用这个一维码类,并设置文件名称和路径,如下:
php
$obj = new \app\common\library\Barcode();
$savePath = '/uploads/barcode/'.time().'.png';
总结
本文介绍了在 PHP 框架中集成一维码生成功能的方法。首先通过 Composer 安装 picqer/php-barcode-generator 三方类库,然后在 common/library 下封装 Barcode 类,提供获取 PNG 流、直接输出图片和保存到本地文件三种方法,最后在其他类中调用即可生成一维码。