编程爱好者之家

tp3.2使用PHP生成二维码

2019-11-19 15:09:55 351

1、原版的PHPQRcode下载地址>> :https://sourceforge.net/projects/phpqrcode/files/

image.png

2、下载后,只需要其中一个文件就可以完成本功能了,如下图所示文件:

image.png

3、将phpqrcode.php放置到:ThinkPHP/Library/Vendor/PHPQRcode/phpqrcode.php (注意大小写哦)
注意:现在放置的是thinkPHP默认的第三方类库目录。

4、创建用户自定义函数文件Application/Home/Common/function.php,放置如下函数:

/**
 * 功能:生成二维码
 * @param string $qr_data   手机扫描后要跳转的网址
 * @param string $qr_level  默认纠错比例 分为L、M、Q、H四个等级,H代表最高纠错能力
 * @param string $qr_size   二维码图大小,1-10可选,数字越大图片尺寸越大
 * @param string $save_path 图片存储路径
 * @param string $save_prefix 图片名称前缀
 */
function createQRcode($save_path,$qr_data='PHP QR Code :)',$qr_level='L',$qr_size=4,$save_prefix='qrcode'){
    if(!isset($save_path)) return '';
    //设置生成png图片的路径
    $PNG_TEMP_DIR = & $save_path;
    //导入二维码核心程序
    vendor('PHPQRcode.phpqrcode');  //PHPQRcode是文件夹名字,phpqrcode就代表phpqrcode.php文件名
    //检测并创建生成文件夹
    if (!file_exists($PNG_TEMP_DIR)){
        mkdir($PNG_TEMP_DIR);
    }
    $filename = $PNG_TEMP_DIR.'test.png';
    $errorCorrectionLevel = 'L';
    if (isset($qr_level) && in_array($qr_level, array('L','M','Q','H'))){
        $errorCorrectionLevel = & $qr_level;
    }
    $matrixPointSize = 4;
    if (isset($qr_size)){
        $matrixPointSize = & min(max((int)$qr_size, 1), 10);
    }
    if (isset($qr_data)) {
        if (trim($qr_data) == ''){
            die('data cannot be empty!');
        }
        //生成文件名 文件路径+图片名字前缀+md5(名称)+.png
        $filename = $PNG_TEMP_DIR.$save_prefix.md5($qr_data.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
        //开始生成
        QRcode::png($qr_data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    } else {
        //默认生成
        QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    }
    if(file_exists($PNG_TEMP_DIR.basename($filename)))
        return basename($filename);
    else
        return FALSE;
}

5、开始调用,假设通过网址/index.php/Home/Index/qrcode访问,那我们相应的在Application/Home/Controller/IndexController.class.php文件里加入方法,如下:

<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    /* 
     * 自定义生成二维码 -xzz0815
     * 使用vender里第三方类库文件,使用GD库
     */
    public function qrcode(){
        $save_path = isset($_GET['save_path'])?$_GET['save_path']:'./Public/qrcode/';  //图片存储的绝对路径
        $web_path = isset($_GET['save_path'])?$_GET['web_path']:'/Public/qrcode/';        //图片在网页上显示的路径
        $qr_data = isset($_GET['qr_data'])?$_GET['qr_data']:'http://www.xxiangfang.com/';
        $qr_level = isset($_GET['qr_level'])?$_GET['qr_level']:'H';
        $qr_size = isset($_GET['qr_size'])?$_GET['qr_size']:'10';
        $save_prefix = isset($_GET['save_prefix'])?$_GET['save_prefix']:'ZETA';
        if($filename = createQRcode($save_path,$qr_data,$qr_level,$qr_size,$save_prefix)){
            $pic = $web_path.$filename;
        }
        echo "<img src='".$pic."'>";
    }


}


同类文章