php 生成二维码

下载 phpqrcode,并引入

1.二维码在线展示(不生成文件,直接在网页上展示)

/*
     * 示例框架 thinkphp5
     * string $con 扫描二维码展示的内容或跳转的url
     * */
    public function Qr($con){
        vendor("phpqrcode.phpqrcode");
        $object = new QRcode();
        ob_end_clean();
        $level=3;
        $size=10;
        $errorCorrectionLevel =intval($level) ;//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        echo $object->png($con,false, $errorCorrectionLevel, $matrixPointSize, 2);
    }
View Code

2.生成文件并保存 

/*
     * 示例框架 thinkphp5  保存二维码到指定位置
     * string $path 保存的路径
     * string $con 扫描二维码展示的内容或跳转的url
     * */
    public function saveQr($pathname,$con){
            if(!is_dir($pathname)) { //若目录不存在则创建之
                mkdir($pathname);
            }
            vendor("phpqrcode.phpqrcode");
//二维码URL参数
//            $text = "http://www.baidu.com";
//二维码图片保存路径(若不生成文件则设置为false)
            $filename = $pathname . "/qrcode_" . time() . ".png";
//二维码容错率,默认L
            $level = "L";
//二维码图片每个黑点的像素,默认4
            $size = '10';
//二维码边框的间距,默认2
            $padding = 2;
//保存二维码图片并显示出来,$filename必须传递文件路径
            $saveandprint = true;
//生成二维码图片
            QRcode::png($con,$filename,$level,$size,$padding,$saveandprint);
    }
View Code

每刷新一次,生成一个文件 

以上两种基本满足需求,但是有的需要加logo怎么办?

3.加logo在线输出

 /*
     * string $value 二维码内容
     * string $logo 准备好的logo图片路径
     * */
    public function Logo($value,$logo){
        header("Content-type: image/png");
        vendor("phpqrcode.phpqrcode");  //引入phpqrcode类文件
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 10;//生成图片大小
        //生成二维码图片
        QRcode::png($value, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = 'qrcode.png';//已经生成的原始二维码图
        if ($logo !== FALSE) {
            $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);
            }
        //输出图片
        ob_end_clean();
        imagepng($QR);
    }
View Code
原文地址:https://www.cnblogs.com/paopao123/p/10622217.html