composer require endroid/qr-code
我安装的是 endroid/qr-code": "^4.6
//引入
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
public function generateQrCode($text)
{
// 创建QR码对象
$result = (new Builder())
->writer(new PngWriter()) // 设置二维码的图像格式为PNG
->writerOptions([]) // 设置写入器选项(这里为空)
->data($text) // 设置二维码的数据内容
->encoding(new Encoding('UTF-8')) // 设置编码方式为UTF-8
->errorCorrectionLevel(new ErrorCorrectionLevelHigh()) // 设置错误纠正级别为高
->size(300) // 设置二维码的大小为300像素
->margin(10) // 设置二维码周围的空白边距为10个模块
->roundBlockSizeMode(new RoundBlockSizeModeMargin()) // 设置圆角块模式
// ->logoPath(__DIR__.'/path/to/logo.png') // 可选:设置二维码中间的logo路径
->labelText('') // 可选:设置标签文本
->labelFont(new NotoSans(20)) // 可选:设置标签文本的字体和大小
->labelAlignment(new LabelAlignmentCenter()) // 可选:设置标签文本对齐方式
->build(); // 构建二维码
// 设置保存路径
$savePath = 'code/' .$text . '.png';
// 确保目录存在
$directory = dirname('.' . DIRECTORY_SEPARATOR . $savePath);
if (!is_dir($directory)) {
mkdir($directory, 0755, true);
}
// 生成二维码图片并保存
file_put_contents('.' . DIRECTORY_SEPARATOR . $savePath, $result->getString());
// 返回图片的相对路径
return $savePath;
}