首先,我们需要下载 phpqrcode 库
地址:https://nchc.dl.sourceforge.net/project/phpqrcode/releases/phpqrcode-2010100721_1.1.4.zip
声明一下:使用的是 Yii 框架
传的参数则为需要写入二维码的内容,这里传了 id
public function createCode1($id) {
$qrcode_path='';
$file_tmp_name='';
$errors=array();
$content = $id; //二维码内容
Yii::$enableIncludePath = false;
Yii::import ('application.extensions.phpqrcode.phpqrcode', 1 );
$tpgs='png';//图片格式
//$bas_path=dirname ( Yii::app ()->BasePath );
$qrcode_bas_path='/web/image/qrcode/';
if(!is_dir($qrcode_bas_path)){
mkdir($qrcode_bas_path, 0777, true);
}
$uniqid_rand=date("Ymdhis").uniqid(). rand(1,1000);
$qrcode_path=$qrcode_bas_path.$uniqid_rand. "_1.".$tpgs;
$qrcode_path_new=$qrcode_bas_path.$uniqid_rand."_2.".$tpgs;
if(empty($errors)){
$errorCorrectionLevel = 'M';//容错级别
$matrixPointSize = 22;//生成图片大小
$matrixMarginSize = 2;//边距大小
//生成二维码图片
QRcode::png($content,$qrcode_path_new, $errorCorrectionLevel, $matrixPointSize, $matrixMarginSize);
$QR = $qrcode_path_new;//已经生成的原始二维码图
$logo = '/web/image/qrcode/logo.png';//准备好的logo图片
if (file_exists($logo)) {
$QR = imagecreatefromstring(file_get_contents($QR));
$logo = imagecreatefromstring(file_get_contents($logo));
$QR_width = imagesx($QR);//二维码图片宽度
$QR_height = imagesy($QR);//二维码图片高度
$logo_width = imagesx($logo);//logo图片宽度
$logo_height = imagesy($logo);//logo图片高度
$logo_qr_width = $QR_width / 5;
$scale = $logo_width/$logo_qr_width;
$logo_qr_height = $logo_height/$scale;
$from_width = ($QR_width - $logo_qr_width) / 2;
//重新组合图片并调整大小
imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
$logo_qr_height, $logo_width, $logo_height);
//输出图片
// header("Content-type: image/png");
imagepng($QR,$qrcode_path);
imagedestroy($QR);
}else{
$qrcode_path=$qrcode_path_new;
}
//$qrcode_path=str_replace($bas_path,'', $qrcode_path);
}else{
$qrcode_path='';
}
$qrcode_path = substr($qrcode_path , 10);
$is_test = strstr($_SERVER['SERVER_NAME'],"test");
$qrcode_path = $is_test ? 'http://test**********'.$qrcode_path : 'http://**********'.$qrcode_path;
return $qrcode_path;
}