phpqrcode生成二维码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<?php /** \* 生成二维码图片(可生成带logo的二维码) \* @param string $data 二维码内容 \* 示例数据:http://www.tf4.cn或weixin://wxpay/bizpayurl?pr=0tELnh9 \* @param string $saveDir 保存路径名(示例:Qrcode) \* @param string $logo 图片logo路径 \* 示例数据:./Public/Default/logo.jpg \* 注意事项:1、前面记得带点(.);2、建议图片Logo正方形,且为jpg格式图片;3、图片大小建议为xx*xx \* 注意:一般用于生成带logo的二维码 \* @return */ public function createQrcode($data,$saveDir="Qrcode",$logo = "") { $rootPath = C("IMAGE_ROOT_PATH"); $path = $saveDir.'/'.date("Y-m-d").'/'; $fileName = uniqid(); if (!is_dir($rootPath.$path)) { mkdir($rootPath.$path,0777,true); } $originalUrl = $path.$fileName.'.png'; Vendor('phpqrcode.phpqrcode'); $object = new \QRcode(); $errorCorrectionLevel = 'L'; //容错级别 $matrixPointSize = 20; //生成图片大小(这个值可以通过参数传进来判断) $object->png($data,$rootPath.$originalUrl,$errorCorrectionLevel, $matrixPointSize, 2); //判断是否生成带logo的二维码 if(file_exists($logo)) { $QR = imagecreatefromstring(file_get_contents($rootPath.$originalUrl)); //目标图象连接资源。 $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 / 4; //组合之后logo的宽度(占二维码的1/5) $scale = $logo_width/$logo_qr_width; //logo的宽度缩放比(本身宽度/组合后的宽度) $logo_qr_height = $logo_height/$scale; //组合之后logo的高度 $from_width = ($QR_width - $logo_qr_width) / 2; //组合之后logo左上角所在坐标点 //重新组合图片并调整大小 //imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中 imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height); //输出图片 imagepng($QR, $rootPath.$originalUrl); imagedestroy($QR); imagedestroy($logo); } $result['errcode'] = 0; $result['errmsg'] = 'ok'; $result['data'] = $originalUrl; return $result; } /** \* 生成临时二维码图片 \* 这里返回的是base64进制图片 \* 一般用于微信扫码支付二维码生成场景 \* @param string $data 二维码内容 \* 示例数据:http://www.tf4.cn或weixin://wxpay/bizpayurl?pr=0tELnh9 \* @return */ public function createTempQrcode($data) { Vendor('phpqrcode.phpqrcode'); $object = new \QRcode(); $errorCorrectionLevel = 'L'; //容错级别 $matrixPointSize = 5; //生成图片大小 //打开缓冲区 ob_start(); //生成二维码图片 $returnData = $object->png($data,false,$errorCorrectionLevel, $matrixPointSize, 2); //这里就是把生成的图片流从缓冲区保存到内存对象上,使用base64_encode变成编码字符串,通过json返回给页面。 $imageString = base64_encode(ob_get_contents()); //关闭缓冲区 ob_end_clean(); $base64 = "data:image/png;base64,".$imageString; $result['errcode'] = 0; $result['errmsg'] = 'ok'; $result['data'] = $base64; return $result; } |