二维码生成 endroid/qr-code 示例

457次阅读
没有评论

原链接 https://www.caizhichao.cn/983.html

1. 使用 composer 命令安装 endroid/QrCode
$ composer require endroid/qr-code

2. 实现代码
// 生成二维码的功能无非就是:/ 二维码上的内容、二维码的尺寸大小、二维码上的 LOGO、二维码上的文字….
// 在 GitHub 上项目仓库里也有给出例子(https://github.com/endroid/qr-code)

<?php
// 引入 composer 自动生成的类加载器
require_once 'vendor/autoload.php';
// 命名空间方式调用 QrCode 类
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Response\QrCodeResponse;

$qrCode = new QrCode();
$qrCode->setText(‘ 设置二维码上的内容 ’); // 设置二维码上的内容
$qrCode->setSize(300); // 二维码尺寸
$qrCode->setWriterByName(‘png’); // 设置输出的二维码图片格式
$qrCode->setMargin(10);
$qrCode->setEncoding(‘UTF-8’);
$qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH()); // 设置二维码的纠错率,可以有 low、medium、quartile、hign 多个纠错率
$qrCode->setForegroundColor([‘r’ => 0, ‘g’ => 0, ‘b’ => 0, ‘a’ => 0]); // 设置二维码的 rgb 颜色和透明度 a,这里是黑色
$qrCode->setBackgroundColor([‘r’ => 255, ‘g’ => 255, ‘b’ => 255, ‘a’ => 0]); // 设置二维码图片的背景底色,这里是白色
// 可能的指定二维码下方的文字,写死 15px 的字体大小,字体
$qrCode->setLabelFontPath(__DIR__.’/vendor/endroid/qr-code/assets/fonts/noto_sans.otf’); // 字体路径
$qrCode->setLabel(‘ 二维码下方的文字 1 ’); // 文字
$qrCode->setLabelFontSize(16); // 字体大小
// 或统一用 setLabel(‘ 二维码下方的文字 ’,’ 字体大小 ’,’ 字体路径 ’,’ 对齐方式 ’) 来设置
$qrCode->setLabel(‘ 二维码下方的文字 2 ′, 16, __DIR__.’/vendor/endroid/qr-code/assets/fonts/noto_sans.otf’, LabelAlignment::CENTER());
$qrCode->setLabelMargin([‘t’=>50]); // 设置标签边距 array(‘t’ => 10,’r’ => 20,’b’ => 10,’l’ => 30)
// 如果要加上 logo 水印,则在调用 setLogoPath 和 setLogoSize 方法
$qrCode->setLogoPath(__DIR__.’/logo.png’); //logo 水印图片的所在的路径
$qrCode->setLogoSize(150, 200); // 设置 logo 水印的大小,单位 px,参数如果是一个 int 数字等比例缩放

// 保存二维码
$qrCode->writeFile(__DIR__.’/qrcode.png’);

// 输出二维码
header(‘Content-Type: ‘.$qrCode->getContentType());
exit($qrCode->writeString());


?>

3、注意
QrCode 生成中文汉字的 label 的时需要引入中文字体,所以需要调用 setLabelFontPath 方法传入一个中文字体的路径,QrCode 默认提供的字体在 \vendor\endroid\qrcode\assets\font 路径下,但 QrCode 类并未默认调用,另外需要使用 UTF8 编码的中文设置 label。

4、各参数详解

参数名 描述 示例
setText 设置文本 https://www.caizhichao.com
setSize 设置二维码的大小,这里二维码应该是正方形的,所以相当于长宽 400
setMargin 设置二维码边距 10
setForegroundColor 设置前景色,RGB 颜色 array(‘r’=> 0,‘g’=> 0,‘b’=> 0,‘a’=> 0)
setBackgroundColor 设置背景色,RGB 颜色 array(‘r’=> 0,‘g’=> 0,‘b’=> 0,‘a’=> 0)
setEncoding 设置编码 utf8
setErrorCorrectionLevel 设置错误级别(low / medium / quartile / high) high
setLogoPath 设置 logo 路径 logo.png
setLogoWidth 设置 logo 大小 50
setLabel 设置标签 test
setLabelFontSize 设置标签字体大小 16
setLabelFontPath 设置标签字体路径 null
setLabelAlignment 设置标签对齐方式(left / center / right) center
setLabelMargin 设置标签边距 array(‘t’=> 10,’r’=> 20,’b’=> 10,’l’=> 30)
setWriterRegistry
setWriter
setWriterByName 写入文件的后缀名 png
setWriterByPath
setWriterByExtension
setValidateResult
writeString
writeDataUri
writeFile 写入文件 test.png

 

正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码