二维码生成器源码

2020年07月17日

引用自:https://github.com/endroid/qr-code
关键字:二维码自动生成 二维码源码 qr-code

通过endroid最新稳定版本构建状态总下载量每月下载许可证

这个库可以帮助你快速生成二维码。利用bacon/bacon qr码生成矩阵和khanamiryan/qrcode检测器解码器验证生成的qr码。进一步扩展了细枝扩展,生成路线,一个工厂和一个Symfony捆绑包,便于安装和配置。提供不同的编写器来生成PNG、SVG、EPS或二进制格式的QR码。

安装
使用Composer安装库进行安装。

安装Composer

curl -sS https://getcomposer.org/installer | php
#下载composer.phar
mv composer.phar /usr/local/bin/composer
#把composer.phar移动到环境下让其变成可执行
composer config -g repo.packagist composer https://packagist.phpcomposer.com
#换中国镜像
composer -V
# 输出:Composer version 1.8.4 2019-02-11 10:52:10

 

安装qrcode

$ composer require endroid/qr-code

 

基本语法

use Endroid\QrCode\QrCode;
$qrCode = new QrCode('Life is too short to be generating QR codes');
header('Content-Type: '.$qrCode->getContentType());
echo $qrCode->writeString();

 

高级语法

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Response\QrCodeResponse;

// Create a basic QR code
$qrCode = new QrCode('Life is too short to be generating QR codes');
$qrCode->setSize(300);
$qrCode->setMargin(10); 

// Set advanced options
$qrCode->setWriterByName('png');
$qrCode->setEncoding('UTF-8');
$qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH());
$qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
$qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
$qrCode->setLabel('Scan the code', 16, __DIR__.'/../assets/fonts/noto_sans.otf', LabelAlignment::CENTER());
$qrCode->setLogoPath(__DIR__.'/../assets/images/symfony.png');
$qrCode->setLogoSize(150, 200);
$qrCode->setValidateResult(false);

// Round block sizes to improve readability and make the blocks sharper in pixel based outputs (like png).
// There are three approaches:
$qrCode->setRoundBlockSize(true, QrCode::ROUND_BLOCK_SIZE_MODE_MARGIN); // The size of the qr code is shrinked, if necessary, but the size of the final image remains unchanged due to additional margin being added (default)
$qrCode->setRoundBlockSize(true, QrCode::ROUND_BLOCK_SIZE_MODE_ENLARGE); // The size of the qr code and the final image is enlarged, if necessary
$qrCode->setRoundBlockSize(true, QrCode::ROUND_BLOCK_SIZE_MODE_SHRINK); // The size of the qr code and the final image is shrinked, if necessary

// Set additional writer options (SvgWriter example)
$qrCode->setWriterOptions(['exclude_xml_declaration' => true]);

// Directly output the QR code
header('Content-Type: '.$qrCode->getContentType());
echo $qrCode->writeString();

// Save it to a file
$qrCode->writeFile(__DIR__.'/qrcode.png');

// Generate a data URI to include image data inline (i.e. inside an <img> tag)
$dataUri = $qrCode->writeDataUri();

 

编码
您可以选择以下值之一进行编码:

ISO-8859-1, ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, ISO-8859-10, ISO-8859-11, ISO-8859-12, ISO-8859-13, ISO-8859-14, ISO-8859-15, ISO-8859-16, Shift_JIS, windows-1250, windows-1251, windows-1252, windows-1256, UTF-16BE, UTF-8, US-ASCII, GBK EUC-KR

 

如果使用条形码扫描仪,则在读取生成的二维码时可能会遇到一些问题。根据您选择的编码,您将拥有与ECI块相对应的额外数据量。有些条形码扫描器没有被编程来解释这个信息块。例如,UTF-8的ECI块为000026,因此上述示例将生成:\000026寿命太短,无法生成二维码。为了确保最大的兼容性,您可以使用ISO-8859-1编码,这是条形码扫描仪使用的默认编码。

可读性

二维码的可读性主要由尺寸、输入长度、纠错级别和图像上任何可能的徽标决定,因此您可以调整这些参数。

使用教程可搜索:qr-code

PHP源码,转载自:https://blog.csdn.net/lqm417626953/article/details/103215874

新建Qrcodes.php二维码生成类

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Response\QrCodeResponse;
use think\Controller;
 
/**
 * 二维码生成类
 * Class Qrcodes
 * @package app\api\controller
 */
class Qrcodes extends Controller
{
    protected $param;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->param = [
            'setSize' => 300,//设置二维码尺寸
            'setWriterByName' => 'png',
            'setMargin' => 5,//设置二维码边界
            'setEncoding' => 'UTF-8',//设置编码
            'setErrorCorrectionLevel' => ErrorCorrectionLevel::HIGH(),//设置容错等级 等级越高识别度越高
            'setLabelStatus' => false,//是否开启二维码标题
            'setLabel' => '这是二维码标题',//设置二维码标题
            'setLogoPathStatus' => false,//是否开启二维码中间logo
            'setLogoPath' => 'logo.png',//设置二维码中间logo
            'setLogoSizeW' => 100,//设置二维码中间logo宽度
            'setLogoSizeH' => 100,//设置二维码中间logo高度
        ];
    }
 
    //生成二维码 --直接输出二维码
    public function returnQrcodeImg($content = '这是二维码内容',$param = [])
    {
        // Create a basic QR code创建一个基本的二维码
        $qrCode = new QrCode($content);
        //设置二维码尺寸
        $qrCode->setSize(isset($param['setSize']) ? $param['setSize'] : $this->param['setSize']);
        // Set advanced options设置高级选项
        $qrCode->setWriterByName(isset($param['setWriterByName']) ? $param['setWriterByName'] : $this->param['setWriterByName']);
        //设置二维码边界
        $qrCode->setMargin(isset($param['setMargin']) ? $param['setMargin'] : $this->param['setMargin']);
        //设置编码
        $qrCode->setEncoding(isset($param['setEncoding']) ? $param['setEncoding'] : $this->param['setEncoding']);
        //设置容错等级 等级越高识别度越高
        $qrCode->setErrorCorrectionLevel(isset($param['setErrorCorrectionLevel']) ? $param['setErrorCorrectionLevel'] : $this->param['setErrorCorrectionLevel']);
        //设置二维码颜色
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        //设置二维码背景颜色
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
        //设置二维码标题 在图片下方显示文字
        //$qrCode->setLabel('Scan the code', 16, __DIR__.'/../assets/fonts/noto_sans.otf', LabelAlignment::CENTER());
        if (isset($param['setLabelStatus']) ? $param['setLabelStatus'] : $this->param['setLabelStatus']) {
            $qrCode->setLabel(isset($param['setLabel']) ? $param['setLabel'] : $this->param['setLabel'], 16, null, LabelAlignment::CENTER());
        }
        //设置二维码中间logo
        if (isset($param['setLogoPathStatus']) ? $param['setLogoPathStatus'] : $this->param['setLogoPathStatus']) {
            $logo = isset($param['setLogoPath']) ? $param['setLogoPath'] : $this->param['setLogoPath'];
            $qrCode->setLogoPath(__DIR__.'/../../../public/static/images/'.$logo);
            //logo尺寸
            $setLogoSizeW = isset($param['setLogoSizeW']) ? $param['setLogoSizeW'] : $this->param['setLogoSizeW'];
            $setLogoSizeH = isset($param['setLogoSizeH']) ? $param['setLogoSizeH'] : $this->param['setLogoSizeH'];
            $qrCode->setLogoSize($setLogoSizeW, $setLogoSizeH);
        }
        //设置二维码内边距,true表示有内边距  false表示没有
        $qrCode->setRoundBlockSize(true);
        //启用内置的验证读取器(默认情况下禁用)
        $qrCode->setValidateResult(false);
        //排除xml声明
        $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);
 
        // Directly output the QR code直接输出二维码
        header('Content-Type: '.$qrCode->getContentType());
        echo $qrCode->writeString();
 
        // Create a response object创建一个响应对象
        //$response = new QrCodeResponse($qrCode);
    }
 
    //生成二维码--保存图片并返回路径
    public function returnQrcodePath($content = '这是二维码内容',$filename = 'qrlogo.png',$param = [])
    {
        // Create a basic QR code创建一个基本的二维码
        $qrCode = new QrCode($content);
        //设置二维码尺寸
        $qrCode->setSize(isset($param['setSize']) ? $param['setSize'] : $this->param['setSize']);
        // Set advanced options设置高级选项
        $qrCode->setWriterByName(isset($param['setWriterByName']) ? $param['setWriterByName'] : $this->param['setWriterByName']);
        //设置二维码边界
        $qrCode->setMargin(isset($param['setMargin']) ? $param['setMargin'] : $this->param['setMargin']);
        //设置编码
        $qrCode->setEncoding(isset($param['setEncoding']) ? $param['setEncoding'] : $this->param['setEncoding']);
        //设置容错等级 等级越高识别度越高
        $qrCode->setErrorCorrectionLevel(isset($param['setErrorCorrectionLevel']) ? $param['setErrorCorrectionLevel'] : $this->param['setErrorCorrectionLevel']);
        //设置二维码颜色
        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        //设置二维码背景颜色
        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
        //设置二维码标题 在图片下方显示文字
        //$qrCode->setLabel('Scan the code', 16, __DIR__.'/../assets/fonts/noto_sans.otf', LabelAlignment::CENTER());
        if (isset($param['setLabelStatus']) ? $param['setLabelStatus'] : $this->param['setLabelStatus']) {
            $qrCode->setLabel(isset($param['setLabel']) ? $param['setLabel'] : $this->param['setLabel'], 16, null, LabelAlignment::CENTER());
        }
        //设置二维码中间logo
        if (isset($param['setLogoPathStatus']) ? $param['setLogoPathStatus'] : $this->param['setLogoPathStatus']) {
            $logo = isset($param['setLogoPath']) ? $param['setLogoPath'] : $this->param['setLogoPath'];
            $qrCode->setLogoPath(__DIR__.'/../../../public/static/images/'.$logo);
            //logo尺寸
            $setLogoSizeW = isset($param['setLogoSizeW']) ? $param['setLogoSizeW'] : $this->param['setLogoSizeW'];
            $setLogoSizeH = isset($param['setLogoSizeH']) ? $param['setLogoSizeH'] : $this->param['setLogoSizeH'];
            $qrCode->setLogoSize($setLogoSizeW, $setLogoSizeH);
        }
        //设置二维码内边距,true表示有内边距  false表示没有
        $qrCode->setRoundBlockSize(true);
        //启用内置的验证读取器(默认情况下禁用)
        $qrCode->setValidateResult(false);
        //排除xml声明
        $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);
 
        // Directly output the QR code直接输出二维码
        //header('Content-Type: '.$qrCode->getContentType());
        //echo $qrCode->writeString();
 
        // Save it to a file保存到文件中
        $qrCode->writeFile(__DIR__.'/../../../public/qrcode/'.$filename);
        return $_SERVER['SERVER_ADDR'].'/public/qrcode/'.$filename;
        // Create a response object创建一个响应对象
        //$response = new QrCodeResponse($qrCode);
    }
}

 

HTML中调用

//直接输出二维码
    public function outputQrcodeImg()
    {
        $qrcode = new \app\common\controller\Qrcodes();
        $param = [
            'setLogoPathStatus' => true,
        ];
        //直接输出二维码
        $qrcode->returnQrcodeImg('https://www.baidu.com/',$param);
    }

    //返回二维码路径
    public function returnQrcodePath()
    {
        $qrcode = new \app\common\controller\Qrcodes();
        $param = [
            'setLogoPathStatus' => true,
        ];
        $filename = mt_rand(1,100000);
        //返回二维码路径
        $path = $qrcode->returnQrcodePath('https://www.baidu.com/',$filename.'.png',$param);
        return $path;

    }

 


sicnature ---------------------------------------------------------------------
Your current IP address is: 3.237.254.197
Your IP address location: 美国 弗吉尼亚州阿什本amazon数据中心 其它参考数据(埃文科技提供)
Your IP address country and region: 美国 美国
Your current browser is:
Your current system is:
Original content, please indicate the source:
同福客栈论坛 | 蟒蛇科普海南乡情论坛 | JiaYu Blog
sicnature ---------------------------------------------------------------------
Welcome to reprint. Please indicate the source http://myzhenai.com.cn/post/3521.html

1 评论

  • 海南胡说 2020年07月18日在12:54 上午

    引用链接:https://www.jianshu.com/p/d508e02508bd

    use Endroid\QrCode\QrCode;
    
    // $content 一般为url地址 当然也可以是文字内容
    $content = 'http://www.baidu.com?rand=' . rand(1000, 9999);
    $qrCode = new QrCode($content);
    // 指定内容类型
    header('Content-Type: '.$qrCode->getContentType());
    // 输出二维码
    echo $qrCode->writeString();
    

     
    首先我们需要在项目中引入qr-code 类文件,composer 现在基本上是通过psr-4 “命名空间”: “路径”的方式进行自动加载,它的位置位于扩展根目录的 composer.json 文件中。
    好了,现在我们引入qr-code 类文件,并尝试输出一个简单的二维码。

    直接输出的二维码怎么应用于项目中呢,一般都是直接写在html 中的 标签中,例如:

    这是一个二维码
    

     

    当然,我们也可以把它存入文件中,生成一个任意格式的图片,比如说:

    $qrCode->writeFile(__DIR__ . '/qrcode.png');
    

     
    我们就可以根据图片路径在页面上展示二维码了

    一个简单的类处理文件,并介绍一下qr-code 常用的一些参数。

    namespace '命名空间';
    
    use Endroid\QrCode\ErrorCorrectionLevel;
    use Endroid\QrCode\LabelAlignment;
    use Endroid\QrCode\QrCode;
    
    class QrcodeComponent
    {
        protected $_qr;
        protected $_encoding = 'UTF-8';
        protected $_size = 300;
        protected $_logo = false;
        protected $_logo_url = '';
        protected $_logo_size = 80;
        protected $_title = false;
        protected $_title_content = '';
        protected $_generate = 'display'; // display-直接显示 writefile-写入文件
        const MARGIN = 10;
        const WRITE_NAME = 'png';
        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) {
            isset($config['generate']) && $this->_generate = $config['generate'];
            isset($config['encoding']) && $this->_encoding = $config['encoding'];
            isset($config['size']) && $this->_size = $config['size'];
            isset($config['display']) && $this->_size = $config['size'];
            isset($config['logo']) && $this->_logo = $config['logo'];
            isset($config['logo_url']) && $this->_logo_url = $config['logo_url'];
            isset($config['logo_size']) && $this->_logo_size = $config['logo_size'];
            isset($config['title']) && $this->_title = $config['title'];
            isset($config['title_content']) && $this->_title_content = $config['title_content'];
        }
    
        /**
         * 生成二维码
         * @param $content 需要写入的内容
         * @return array | page input
         */
        public function create($content) {
            $this->_qr = new QrCode($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->setBackgroundColor(self::BACKGROUND_COLOR);
            if ($this->_title) {
                $this->_qr->setLabel($this->_title_content, 16, '字体地址', LabelAlignment::CENTER);
            }
            if ($this->_logo) {
                $this->_qr->setLogoPath($this->_logo_url);
                $this->_qr->setLogoWidth($this->_logo_size);
                $this->_qr->setRoundBlockSize(true);
            }
            $this->_qr->setValidateResult(false);
    
            if ($this->_generate == 'display') {
                // 前端调用 例:
                header('Content-Type: ' . $this->_qr->getContentType());
                return $this->_qr->writeString();
            } else if ($this->_generate == 'writefile') {
                return $this->_qr->writeString();
            } else {
                return ['success' => false, 'message' => 'the generate type not found', 'data' => ''];
            }
        }
    
        /**
         * 生成文件
         * @param $file_name 目录文件 例: /tmp
         * @return array
         */
        public function generateImg($file_name) {
            $file_path = $file_name . DS . uniqid() . '.' . self::WRITE_NAME;
    
            if (!file_exists($file_name)) {
                mkdir($file_name, 0777, true);
            }
    
            try {
                $this->_qr->writeFile($file_path);
                $data = [
                    'url' => $file_path,
                    'ext' => self::WRITE_NAME,
                ];
                return ['success' => true, 'message' => 'write qrimg success', 'data' => $data];
            } catch (Exception $e) {
                return ['success' => false, 'message' => $e->getMessage(), 'data' => ''];
            }
        }
    }
    

     
    使用方法:

    use '命名空间';
    $qr_url = 'http://www.baidu.com?id=' . rand(1000, 9999);
    $file_name = '/tmp';
    
    // 直接输出
    $qr_code = new QrcodeComponent();
    $qr_img = qr_code->create($qr_url);
    echo $qr_img;
    
    // 生成文件
    $config = [
        'generate' => 'writefile',
    ];
    $qr_code = new QrcodeComponent($config);
    $qr_img = $qr_code->create($qr_url);
    $rs = $qr_code->generateImg($file_name);
    print_r($rs);
    

     
    常用参数解释:

    setSize - 二维码大小 px
    setWriterByName - 写入文件的后缀名
    setMargin - 二维码内容相对于整张图片的外边距
    setEncoding - 编码类型
    setErrorCorrectionLevel - 容错等级,分为L、M、Q、H四级
    setForegroundColor - 前景色
    setBackgroundColor - 背景色
    setLabel - 二维码标签
    setLogoPath - 二维码logo路径
    setLogoWidth - 二维码logo大小 px
    

     

发表评论

电子邮件地址不会被公开。 必填项已用*标注