使用php 生成二维码,主要是可以自定义样式。一般情况下,建议使用前端qrcode.min.js生成即可。
<?php
/*
* @Description: 二维码
* @ComposerRequire: composer require endroid/qr-code
* @ComposerRemove: composer require endroid/qr-code
* @Author: 阿海 <764882431@qq.com>
* @Date: 2020-11-10 15:19:53
* @LastEditTime: 2020-12-29 10:29:52
* @LastEditors: 阿海
*/
namespace app\common\library;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
class PHPQrcode
{
protected $_qr;
protected $_encoding = 'UTF-8'; // 编码类型
protected $_size = 300; // 二维码大小
protected $_logo = false; // 是否需要带logo的二维码
protected $_logo_url = ''; // logo图片路径
protected $_logo_size = 80; // logo大小
protected $_title = false; // 是否需要二维码title
protected $_title_content = ''; // title内容
protected $_generate = 'display'; // display-直接显示 writefile-写入文件 download-下载 base64-编码文件
protected $_file_save_path = 'runtime/uploads/qrcode/'; // 写入文件路径
protected $_foreground_color = ['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]; // 前景色
protected $_background_color = ['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]; // 背景色
const MARGIN = 10; // 二维码内容相对于整张图片的外边距
const WRITE_NAME = 'png'; // 写入文件的后缀名
protected $_content = ""; //二维码内容
//const FOREGROUND_COLOR = ['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]; // 前景色
//const BACKGROUND_COLOR = ['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]; // 背景色
public function __construct($config)
{
$this->_generate = isset($config['generate']) ? $config['generate']:$this->_generate;
$this->_encoding = isset($config['encoding']) ? $config['encoding']:$this->_encoding;
$this->_size = isset($config['size']) ? $config['size']:$this->_size;
$this->_logo = isset($config['logo']) ? $config['logo']:$this->_logo;
$this->_logo_url = isset($config['logo_url']) ? $config['logo_url']:$this->_logo_url;
$this->_logo_size = isset($config['logo_size']) ? $config['logo_size']:$this->_logo_size;
$this->_title = isset($config['title']) ? $config['title']: $this->_title;
$this->_title_content = isset($config['title_content']) ? $config['title_content']: $this->_title_content;
$this->_file_save_path = isset($config['file_save_path']) ? $config['file_save_path']:$this->_file_save_path;
$this->_foreground_color = isset($config['foreground_color']) ? $config['foreground_color']:$this->_foreground_color;
$this->_background_color = isset($config['background_color']) ? $config['background_color']: $this->_background_color;
$this->_content = isset($config['content']) ? $config['content']: $this->_content;
}
/**
* 生成二维码
* @return array | page input
* @throws \Endroid\QrCode\Exception\InvalidPathException
* @throws \Endroid\QrCode\Exception\InvalidWriterException
*/
public function createServer()
{
if ($this->_generate == 'display') {
return $this->display();
} else if ($this->_generate == 'download') {
return $this->download();
} else if ($this->_generate == 'base64') {
return $this->toBase64();
} else if ($this->_generate == 'writefile') {
} else {
app("api_result")->echoJson(-3,['msg'=>'the generate type not found,display or base64 or writefile or download support for optional parameter']);
}
}
/**
* 保存图片
* @param string $content 二维码内容
* @param string $path 保存的路径
* @return 图片路径
*/
public function save($content = '',$path =''){
if(!empty($content)){
$this->_content = $content;
}
if(!empty($path)){
$this->_file_save_path = $path;
}
$this->_qr = $this->createQrcode();
return $this->generateImg();
}
/**
* @param string $content 二维码内容
* 返回base64的图片数据
*/
public function base64($content = ''){
if(!empty($content)){
$this->_content = $content;
}
$this->_qr = $this->createQrcode();
return $this->_qr->writeDataUri();
}
/**
* 下载二维码,会在服务器中保存一份
* @param string $content 二维码内容
* @param string $path 保存的路径--这里的下载是先把图片生成在服务器,然后再下载下来
*/
public function download($content='',$path='runtime/uploads/qrcode/download/'){
if(!empty($path)){
$this->_file_save_path = $path;
}
if(!empty($content)){
$this->_content = $content;
}
$this->_qr = $this->createQrcode();
$result = $this->generateImg();
if ($result['code'] == 0) {
header('Content-Disposition:attachment;filename=' . basename($result['data']['path']));
header('Content-Length:' . filesize($result['data']['path']));
readfile($result['data']['path']);
app("api_result")->echoJson(0,['msg'=>'download qrimg success']);
} else {
app("api_result")->echoJson(-3,['msg'=>$result['errorMsg']]);
}
}
/**
* @param string $content 二维码的内容
* 线上直接显示--链接就是图片
* 前端调用 例:<img src="http://localhost/qr.php?url=base64_url_string">
*/
public function display($content = ''){
if(!empty($content)){
$this->_content = $content;
}
$this->createQrcode();
header('Content-Type: ' . $this->_qr->getContentType());
return $this->_qr->writeString();
}
/**
* 初始化数据
*/
private function createQrcode(){
if(empty($this->_content)){
app("api_result")->echoJson(-3,['msg'=>'do not set the qrcode content']);
}
$this->_qr = new QrCode($this->_content);
$this->_qr->setSize($this->_size);
$this->_qr->setWriterByName(self::WRITE_NAME);
$this->_qr->setMargin(self::MARGIN);
$this->_qr->setEncoding($this->_encoding);
$this->_qr->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH()); // 容错率
//$this->_qr->setForegroundColor(self::FOREGROUND_COLOR);
$this->_qr->setForegroundColor($this->_foreground_color);
//$this->_qr->setBackgroundColor(self::BACKGROUND_COLOR);
$this->_qr->setBackgroundColor($this->_background_color);
// 是否需要title
if ($this->_title) {
$this->_qr->setLabel($this->_title_content, 16, null, LabelAlignment::CENTER);
}
// 是否需要logo
if ($this->_logo) {
$this->_qr->setLogoPath($this->_logo_url);
$this->_qr->setLogoWidth($this->_logo_size);
}
$this->_qr->setValidateResult(false);
return $this->_qr;
}
/**
* 生成文件 返回图片路径
* @return array
*/
private function generateImg()
{
$path = env('root_path').$this->_file_save_path;
$file_save_path = $path . uniqid() . '.' . self::WRITE_NAME;
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
try {
$this->_qr->writeFile($file_save_path);
$data = [
'path' => $file_save_path ,
'url'=>substr($file_save_path,strlen(env('root_path'))),
'ext' => self::WRITE_NAME,
];
return app("api_result")->returnArray(0,['msg'=>'write qrimg success','data'=>$data]);
} catch (\Exception $e) {
return app("api_result")->echoJson(-3,['msg'=>$e->getMessage()]);
}
}
}