PHP根据指定url生成二维码图片

一、composer安装

http://packagist.p2hp.com/packages/codeitnowin/barcode

二、使用

调用generateQrCode()方法即可实现生成二维码图片并输出下载给用户

<?php
namespace manage\Test;

use CodeItNow\BarcodeBundle\Utils\QrCode;
use common\extensions\Helper;
use yii\helpers\FileHelper;

class TestService
{
    /**
     * 生成二维码图片
     * @return array
     * @throws \yii\base\Exception
     */
    public function generateQrCode($uid = 400570)
    {
        // 进行基础定义
        $url = 'http://www.xiaobudiu.top?uid=' . $uid;//定义需要生成二维码图片的url
        $out_put_file_name = '小卜丢饭团子'.date('His');//定义生成的二维码图片名称
        $tmp_path = \Yii::$app->basePath.'/runtime/tmp_file/';// 定义存储临时文件的临时文件夹路径

        // 判断如果临时文件夹不存在,则创建临时文件夹(用于存储生成的临时二维码图片)
        $generate_res = $this->generateDir($tmp_path);
        if (!$generate_res) {
            return Helper::msg('0', '创建图片临时文件夹失败');
        }

        // 根据url生成二维码图片base64 str
        $image_base64_str = $this->generateImgBase64Str($url);
        // 将base64转图片格式,并将图片存储到指定文件夹(返回值为图片的绝对路径)
        $file = $this->base64_to_img($image_base64_str, $tmp_path, 'admin_');
        if (!$file) {
            return Helper::msg('0', '生成二维码图片失败');
        }

        // 设置请求头
        header('Content-Disposition:attachment;filename='.$out_put_file_name.'.png');
        header('Content-Length:' . filesize($file));
        // 读取文件并写入到输出缓冲
        readfile($file);
        // 为了节省本地资源,删除临时图片(可选)
        unlink($file);
    }


    /**
     * 判断目录是否存在,如果不存在,则创建,存在则返回
     * @param $path
     * @return mixed
     * @throws \yii\base\Exception
     */
    public static function generateDir($path)
    {
        if (FileHelper::createDirectory($path, 0775, true)) {
            return $path;
        }
        return false;
    }


    /**
     * 根据url生成二维码图片base64 str
     */
    public function generateImgBase64Str($url)
    {
        $qr_code = new QrCode();
        $image_base64_str = $qr_code->setText($url)->setImageType(QrCode::IMAGE_TYPE_PNG)->generate();// 生成图片base64 str
        return $image_base64_str;
    }


    /**
     * base64转图片格式,并将图片存储到指定文件夹
     */
    public function base64_to_img($base64_str, $path, $prefix = null)
    {
        if($base64_str != ''){
            $output_file_name = $prefix.time().rand(100,999).'.png';
            $path .= $output_file_name;
            $file_handle = fopen($path, "wb");
            fwrite($file_handle, base64_decode($base64_str));
            fclose($file_handle);
            return($path);
        }
        return false;
    }

    
# -------------------------- 备注方法,给不使用yii的同学参考 -------------------------
    /**
     * yii框架中的创建文件夹方法,即上面调用的同名方法
     * @param $path
     * @param int $mode
     * @param bool $recursive
     * @return bool
     * @throws \yii\base\Exception
     */
    public function createDirectory($path, $mode = 0775, $recursive = true)
    {
        if (is_dir($path)) {
            return true;
        }
        $parentDir = dirname($path);
        // recurse if parent dir does not exist and we are not at the root of the file system.
        if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
            static::createDirectory($parentDir, $mode, true);
        }
        try {
            if (!mkdir($path, $mode)) {
                return false;
            }
        } catch (\Exception $e) {
            if (!is_dir($path)) {
                // throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
                throw new \Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
            }
        }
        try {
            return chmod($path, $mode);
        } catch (\Exception $e) {
            // throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
            throw new \Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
        }
    }
}

3、效果

浏览器直接进行下载:

打开下载的图片,效果:

发布了137 篇原创文章 · 获赞 174 · 访问量 255万+

猜你喜欢

转载自blog.csdn.net/m_nanle_xiaobudiu/article/details/85340083