一。下載phpqrcode:https://sourceforge.net/projects/phpqrcode/
將phpqrcode.php重命名為符合thinkPHP文件規則的文件名class.phpqrcode.php,放置到:ThinkPHP/Library/Vendor/PHPQRcode/class.phpqrcode.php (注意大小寫哦)
注意:現在放置的是thinkPHP默認的第三方類庫目錄,如果在index.php定義了如define('VENDOR_PATH',APP_PATH.'Common/Vendor/'); 那么文件放置的路徑要與之相同,免得出現class 'QRcode' not found情況。
二創建用戶自定義函數文件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.class#phpqrcode'); //注意這里的大小寫哦,不然會出現找不到類,PHPQRcode是文件夾名字,class#phpqrcode就代表class.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; }
三 開始調用,假設通過網址/?m=home&c=index&a=qrcode訪問,那我們相應的在Application/Home/Controller/IndexController.class.php文件里加入方法,如下:
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function index(){ } public function qrcode(){ $save_path = isset($_GET['save_path'])?$_GET['save_path']:ROOT_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.zetadata.com.cn/'; $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."'>"; } }
四 附不同參數生成的不同圖片尺寸:

轉載 http://www.thinkphp.cn/Uploads/editor/2015-06-17/558187c85c6d9.png
