search
HomeBackend DevelopmentPHP TutorialHow to generate QR code using Thinkphp3.2 and phpqrcode

First, download phpqrcode and extract it to the project ThinkPHP\Library\Vendor directory.
Index_index.html (the template can be configured by yourself)

    尺寸大小:           
    边距大小:         
            1px
            2px
            3px
            5px
        
    容错级别:        
        Low (7%)
        Medium (15%)
        Quartile (25%)
        High (30%)       
    二维码内容:            
    二维码logo:

Controller: IndexController.class.php

<?php
namespace Home\Controller;use Think\Controller;class IndexController extends Controller {    
public function index(){        
$config = array(            
                        &#39;maxSize&#39;    =>    3145728,
            &#39;rootPath&#39;   =>    &#39;./upload/&#39;,
            &#39;savePath&#39;   =>    &#39;&#39;,
            &#39;saveName&#39;   =>    array(&#39;uniqid&#39;,&#39;&#39;),
            &#39;exts&#39;       =>    array(&#39;jpg&#39;, &#39;gif&#39;, &#39;png&#39;, &#39;jpeg&#39;),
            &#39;autoSub&#39;    =>    true,
            &#39;subName&#39;    =>    array(&#39;date&#39;,&#39;Ymd&#39;),
        );        $upload = new \Think\Upload($config);// 实例化上传类
        // 上传单个文件
        $info   =   $upload->uploadOne($_FILES[&#39;test&#39;]);        
        if(!$info) {// 上传错误提示错误信息
            $qrcode_path_new = &#39;./Public/Home/images/code&#39;.&#39;_&#39;.date("Ymdhis").&#39;.png&#39;;            
            $content = $_POST[&#39;content&#39;];            
            $matrixPointSize = $_POST[&#39;matrixPointSize&#39;];            
            $matrixMarginSize = $_POST[&#39;matrixMarginSize&#39;];            
            $errorCorrectionLevel = $_POST[&#39;errorCorrectionLevel&#39;];
            makecode_no_pic($content,$qrcode_path_new,$matrixPointSize,$matrixMarginSize,$errorCorrectionLevel);            $this->assign(&#39;img&#39;,$qrcode_path_new);
        }else{            
        $qrcode_path = "./upload/".
        $info[&#39;savepath&#39;].
        $info[&#39;savename&#39;];            
        $content = $_POST[&#39;content&#39;];            
        $matrixPointSize = $_POST[&#39;matrixPointSize&#39;];            
        $matrixMarginSize = $_POST[&#39;matrixMarginSize&#39;];            
        $errorCorrectionLevel = $_POST[&#39;errorCorrectionLevel&#39;];            
        $url = "./upload/qrcode/".date("YmdHis").".png";
            makecode($qrcode_path,$content,$matrixPointSize,$matrixMarginSize,$errorCorrectionLevel,$url);            $this->assign(&#39;img&#39;,$url);
            }        
            $this->display();
    }
}

Then create a new function.php under the project Application/Home/Common

<?php
function makecode($qrcode_path,$content,$matrixPointSize,$matrixMarginSize,$errorCorrectionLevel,$url){        /**     参数详情:
         *      $qrcode_path:logo地址
         *      $content:需要生成二维码的内容
         *      $matrixPointSize:二维码尺寸大小
         *      $matrixMarginSize:生成二维码的边距
         *      $errorCorrectionLevel:容错级别
         *      $url:生成的带logo的二维码地址
         * */
        ob_clean ();
        Vendor(&#39;phpqrcode.phpqrcode&#39;);        
        $object = new \QRcode();        
        $qrcode_path_new = &#39;./Public/Home/images/code&#39;.&#39;_&#39;.date("Ymdhis").&#39;.png&#39;;//定义生成二维码的路径及名称
        $object::png($content,
        $qrcode_path_new, 
        $errorCorrectionLevel, 
        $matrixPointSize, 
        $matrixMarginSize);        
        $QR = imagecreatefromstring(file_get_contents($qrcode_path_new));//imagecreatefromstring:创建一个图像资源从字符串中的图像流
        $logo = imagecreatefromstring(file_get_contents($qrcode_path));        
        $QR_width = imagesx($QR);// 获取图像宽度函数
        $QR_height = imagesy($QR);//获取图像高度函数
        $logo_width = imagesx($logo);// 获取图像宽度函数
        $logo_height = imagesy($logo);//获取图像高度函数
        $logo_qr_width = $QR_width / 4;//logo的宽度
        $scale = $logo_width / $logo_qr_width;//计算比例
        $logo_qr_height = $logo_height / $scale;//计算logo高度
        $from_width = ($QR_width - $logo_qr_width) / 2;//规定logo的坐标位置
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, 
        $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);        /**     
        imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
         *      参数详情:
         *      $dst_image:目标图象连接资源。
         *      $src_image:源图象连接资源。
         *      $dst_x:目标 X 坐标点。
         *      $dst_y:目标 Y 坐标点。
         *      $src_x:源的 X 坐标点。
         *      $src_y:源的 Y 坐标点。
         *      $dst_w:目标宽度。
         *      $dst_h:目标高度。
         *      $src_w:源图象的宽度。
         *      $src_h:源图象的高度。
         * */
        Header("Content-type: image/png");        //$url:定义生成带logo的二维码的地址及名称
        imagepng($QR,$url);
    }    function makecode_no_pic($content,$qrcode_path_new,$matrixPointSize,$matrixMarginSize,$errorCorrectionLevel){        ob_clean ();
        Vendor(&#39;phpqrcode.phpqrcode&#39;);        
        $object = new \QRcode();        
        $object::png($content,$qrcode_path_new, 
        $errorCorrectionLevel, 
        $matrixPointSize, 
        $matrixMarginSize);
    }

When there is no picture uploaded, the QR code generated for me is just a simple QR code. Only when When a logo is uploaded, a QR code with the logo will be generated.

The picture below is the QR code generated when there is no logo:

The picture below is The QR code generated when a picture is uploaded:

The above is the detailed content of How to generate QR code using Thinkphp3.2 and phpqrcode. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool