现在很多框架都支持且仅支持使用composer来安装和管理,比如最新的thinkphp6,对于很多没接触过composer的人很迷茫,但在百度搜thinkphp6怎么生成二维码,大多没结果。
刚好最近在用thinkphp6重写一个项目,遇到生成二维码这块,显然之前的phpqrcode是不能再用了,而且composer上面也没有phpqrcode的版本,所以呢,用Endroid/QrCode替代,写好来分享给大家。
composer的介绍和安装今天先不说,直接进入“使用composer安装和使用endroid/QrCode来生成二维码”。
1、安装composer
2、使用composer命令安装Endroid/QrCode
composer require endroid/qr-code
3、实现代码
//生成二维码的功能无非就是:/二维码上的内容、二维码的尺寸大小、二维码上的LOGO、二维码上的文字….
在项目目录vendor\endroid\qr-code\src\QrCode.php
<?php
declare(strict_types=1);
namespace Endroid\QrCode;
use BaconQrCode\Encoder\Encoder;
use Endroid\QrCode\Exception\InvalidPathException;
use Endroid\QrCode\Exception\UnsupportedExtensionException;
use Endroid\QrCode\Writer\WriterInterface;
class QrCode implements QrCodeInterface
{
const LABEL_FONT_PATH_DEFAULT = __DIR__.'/../assets/fonts/noto_sans.otf';
private $text;
private $size = 300;
private $margin = 10;
private $foregroundColor = [
'r' => 0,
'g' => 0,
'b' => 0,
'a' => 0,
];
private $backgroundColor = [
'r' => 255,
'g' => 255,
'b' => 255,
'a' => 0,
];
private $encoding = 'UTF-8';
private $roundBlockSize = true;
private $errorCorrectionLevel;
private $logoPath;
private $logoWidth;
private $logoHeight;
private $label;
private $labelFontSize = 16;
private $labelFontPath = self::LABEL_FONT_PATH_DEFAULT;
private $labelAlignment;
private $labelMargin = [
't' => 0,
'r' => 10,
'b' => 10,
'l' => 10,
];
private $writerRegistry;
private $writer;
private $writerOptions = [];
private $validateResult = false;
public function __construct(string $text = '')
{
$this->text = $text;
$this->errorCorrectionLevel = new ErrorCorrectionLevel(ErrorCorrectionLevel::LOW);
$this->labelAlignment = new LabelAlignment(LabelAlignment::CENTER);
$this->createWriterRegistry();
}
public function setText(string $text): void
{
$this->text = $text;
}
public function getText(): string
{
return $this->text;
}
public function setSize(int $size): void
{
$this->size = $size;
}
public function getSize(): int
{
return $this->size;
}
public function setMargin(int $margin): void
{
$this->margin = $margin;
}
public function getMargin(): int
{
return $this->margin;
}
public function setForegroundColor(array $foregroundColor): void
{
if (!isset($foregroundColor['a'])) {
$foregroundColor['a'] = 0;
}
foreach ($foregroundColor as &$color) {
$color = intval($color);
}
$this->foregroundColor = $foregroundColor;
}
public function getForegroundColor(): array
{
return $this->foregroundColor;
}
public function setBackgroundColor(array $backgroundColor): void
{
if (!isset($backgroundColor['a'])) {
$backgroundColor['a'] = 0;
}
foreach ($backgroundColor as &$color) {
$color = intval($color);
}
$this->backgroundColor = $backgroundColor;
}
public function getBackgroundColor(): array
{
return $this->backgroundColor;
}
public function setEncoding(string $encoding): void
{
$this->encoding = $encoding;
}
public function getEncoding(): string
{
return $this->encoding;
}
public function setRoundBlockSize(bool $roundBlockSize): void
{
$this->roundBlockSize = $roundBlockSize;
}
public function getRoundBlockSize(): bool
{
return $this->roundBlockSize;
}
public function setErrorCorrectionLevel(ErrorCorrectionLevel $errorCorrectionLevel): void
{
$this->errorCorrectionLevel = $errorCorrectionLevel;
}
public function getErrorCorrectionLevel(): ErrorCorrectionLevel
{
return $this->errorCorrectionLevel;
}
public function setLogoPath(string $logoPath): void
{
$logoPath = realpath($logoPath);
if (!is_file($logoPath)) {
throw new InvalidPathException('Invalid logo path: '.$logoPath);
}
$this->logoPath = $logoPath;
}
public function getLogoPath(): ?string
{
return $this->logoPath;
}
public function setLogoSize(int $logoWidth, int $logoHeight = null): void
{
$this->logoWidth = $logoWidth;
$this->logoHeight = $logoHeight;
}
public function setLogoWidth(int $logoWidth): void
{
$this->logoWidth = $logoWidth;
}
public function getLogoWidth(): ?int
{
return $this->logoWidth;
}
public function setLogoHeight(int $logoHeight): void
{
$this->logoHeight = $logoHeight;
}
public function getLogoHeight(): ?int
{
return $this->logoHeight;
}
public function setLabel(string $label, int $labelFontSize = null, string $labelFontPath = null, string $labelAlignment = null, array $labelMargin = null): void
{
$this->label = $label;
if (null !== $labelFontSize) {
$this->setLabelFontSize($labelFontSize);
}
if (null !== $labelFontPath) {
$this->setLabelFontPath($labelFontPath);
}
if (null !== $labelAlignment) {
$this->setLabelAlignment($labelAlignment);
}
if (null !== $labelMargin) {
$this->setLabelMargin($labelMargin);
}
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabelFontSize(int $labelFontSize): void
{
$this->labelFontSize = $labelFontSize;
}
public function getLabelFontSize(): ?int
{
return $this->labelFontSize;
}
public function setLabelFontPath(string $labelFontPath): void
{
$resolvedLabelFontPath = realpath($labelFontPath);
if (!is_string($resolvedLabelFontPath) || !is_file($resolvedLabelFontPath)) {
throw new InvalidPathException('Invalid label font path: '.$labelFontPath);
}
$this->labelFontPath = $resolvedLabelFontPath;
}
public function getLabelFontPath(): ?string
{
return $this->labelFontPath;
}
public function setLabelAlignment(string $labelAlignment): void
{
$this->labelAlignment = new LabelAlignment($labelAlignment);
}
public function getLabelAlignment(): ?string
{
return $this->labelAlignment->getValue();
}
public function setLabelMargin(array $labelMargin): void
{
$this->labelMargin = array_merge($this->labelMargin, $labelMargin);
}
public function getLabelMargin(): ?array
{
return $this->labelMargin;
}
public function setWriterRegistry(WriterRegistryInterface $writerRegistry): void
{
$this->writerRegistry = $writerRegistry;
}
public function setWriter(WriterInterface $writer): void
{
$this->writer = $writer;
}
public function getWriter(string $name = null): WriterInterface
{
if (!is_null($name)) {
return $this->writerRegistry->getWriter($name);
}
if ($this->writer instanceof WriterInterface) {
return $this->writer;
}
return $this->writerRegistry->getDefaultWriter();
}
public function setWriterOptions(array $writerOptions): void
{
$this->writerOptions = $writerOptions;
}
public function getWriterOptions(): array
{
return $this->writerOptions;
}
private function createWriterRegistry()
{
$this->writerRegistry = new WriterRegistry();
$this->writerRegistry->loadDefaultWriters();
}
public function setWriterByName(string $name)
{
$this->writer = $this->getWriter($name);
}
public function setWriterByPath(string $path): void
{
$extension = pathinfo($path, PATHINFO_EXTENSION);
$this->setWriterByExtension($extension);
}
public function setWriterByExtension(string $extension): void
{
foreach ($this->writerRegistry->getWriters() as $writer) {
if ($writer->supportsExtension($extension)) {
$this->writer = $writer;
return;
}
}
throw new UnsupportedExtensionException('Missing writer for extension "'.$extension.'"');
}
public function writeString(): string
{
return $this->getWriter()->writeString($this);
}
public function writeDataUri(): string
{
return $this->getWriter()->writeDataUri($this);
}
public function writeFile(string $path): void
{
$this->getWriter()->writeFile($this, $path);
}
public function getContentType(): string
{
return $this->getWriter()->getContentType();
}
public function setValidateResult(bool $validateResult): void
{
$this->validateResult = $validateResult;
}
public function getValidateResult(): bool
{
return $this->validateResult;
}
public function getData(): array
{
$baconErrorCorrectionLevel = $this->errorCorrectionLevel->toBaconErrorCorrectionLevel();
$baconQrCode = Encoder::encode($this->text, $baconErrorCorrectionLevel, $this->encoding);
$matrix = $baconQrCode->getMatrix()->getArray()->toArray();
foreach ($matrix as &$row) {
$row = $row->toArray();
}
$data = ['matrix' => $matrix];
$data['block_count'] = count($matrix[0]);
$data['block_size'] = $this->size / $data['block_count'];
if ($this->roundBlockSize) {
$data['block_size'] = intval(floor($data['block_size']));
}
$data['inner_width'] = $data['block_size'] * $data['block_count'];
$data['inner_height'] = $data['block_size'] * $data['block_count'];
$data['outer_width'] = $this->size + 2 * $this->margin;
$data['outer_height'] = $this->size + 2 * $this->margin;
$data['margin_left'] = ($data['outer_width'] - $data['inner_width']) / 2;
if ($this->roundBlockSize) {
$data['margin_left'] = intval(floor($data['margin_left']));
}
$data['margin_right'] = $data['outer_width'] - $data['inner_width'] - $data['margin_left'];
return $data;
}
}
<?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());
?>
4、注意
QrCode生成中文汉字的label的时需要引入中文字体,所以需要调用setLabelFontPath方法传入一个中文字体的路径,QrCode默认提供的字体在\vendor\endroid\qrcode\assets\font路径下,但QrCode类并未默认调用,另外需要使用UTF8编码的中文设置label。
5、各参数详解
参数名 描述 示例
setText 设置文本 https://www.dkewl.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
6、方法调用
$this->QrCode($data);//方法调用
/**
* 生成二维码方法
*/
public function QrCode($order_number)
{
$content = 'http://fanxin.me:8080?order_number=' . $order_number;
$url = root_path() . '/public/upload_resource/qrcode/' . $order_number . '.png';//存框架的位置
$code_url = 'http://fanxin.me:8080/upload_resource/qrcode/' . $order_number . '.png';//二维码的访问地址
$qrCode=new QrCode($content);
// 指定内容类型
header('Content-Type: ' . $qrCode->getContentType());
// 输出二维码
$qrCode->writeFile($url);
return $code_url;
}
关注不迷路
扫码下方二维码,关注宇凡盒子公众号,免费获取最新技术内幕!
评论0