生成小程序菊花碼(生成菊花碼、更換中間logo、更改圖片尺寸,加文字)

 

 

<?php
/**
 * 獲取小程序二維碼
 */
class getMiniQrcode {

    public $db = '';

    public function __construct() {
        $this->db = mysqli_connect('', '', '', '');
    }

    public function index($id = 0) {
        if (!$id) {
            echo 'no input ID';
            return;
        }
        $res = mysqli_query($this->db, "select id,command,device_num from sys_equipment where id=" . $id);
        $res = mysqli_fetch_assoc($res);
        $ARRAY = [];
        $ARRAY[] = $res;
        // 獲取token
        $ACCESS_TOKEN = $this->getAccesstoken();
        // 準備進入小程序的參數
        $color = [
            'r' => 0,
            'g' => 0,
            'b' => 0,
        ];
        foreach ($ARRAY as $key => $value) {
            $param = [
                'path' => "pages/shop/shop?mac=" . $value['command'],
                'auto_color' => false,
                'line_color' => $color,
                'is_hyaline' => false,
                'width' => 1280,
            ];
            // 請求微信生成二維碼接口
            $request_url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $ACCESS_TOKEN;
            $result = $this->httpRequest($request_url, json_encode($param), "POST");

            $myPic = 'http://www.yoursite.com/path/to/logo.jpg';
            // 生成圓形自定義圖片
            $logo = $this->yuanImg($myPic);
            //二維碼與自定義圖片結合
            $sharePic = $this->qrcodeWithLogo($result, $logo);

            // 準備文件名
            // $filename = date('YmdHis') . md5(time() . mt_rand(10, 99)) . '.png';
            $filename = $value['id'] . '_small.png';
            $filepath = "./" . $filename;
            // 將二進制圖片寫入文件
            if (@$fp = fopen($filepath, 'w+')) {
                fwrite($fp, $sharePic);
                fclose($fp);
            }
            
            if (file_exists($filepath)) {
                echo 'success';
                // 這裏的background.png爲比二維碼大的一張白色圖片, 多出的空白的地方,用來寫文字
                $background = imagecreatefrompng('http://www.yoursite.com/path/to/background.png');
                $img = imagecreatefrompng('./' . $filename);
                // 合併
                imagecopy($background, $img, 0, 0, 0, 0, 1280, 1280);
                // 字體文件包
                $font = './font.ttf';
                $color = imagecolorallocate($background, 0, 0, 0);
                // 要寫入的文本
                $text = 'SN: ' . $value['device_num'];
                imagettftext($background, 60, 0, 170, 1350, $color, $font, $text);

                //生成圖像
                imagepng($background);
                imagepng($background, './' . $value['id'] . '.png');
            }
        }
    }
    
    /**
     * [獲取AccessToken]
     * @return [type] [description]
     */
    public function getAccesstoken() {
        header('content-type:text/html;charset=utf-8');
        //配置APPID、APPSECRET
        $APPID = '';
        $APPSECRET = '';
        // 請求地址
        $getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

        $ACCESS_TOKEN = "";

        $jsonResult = $this->httpRequest($getTokenUrl);
        $jsonResult = json_decode($jsonResult, true);

        $ACCESS_TOKEN = $jsonResult["access_token"];
        return $ACCESS_TOKEN;
    }
    /**
     * 剪切圖片爲圓形
     * @param  $picture 圖片數據流 好比file_get_contents(imageurl)返回的東東
     * @return 圖片數據流
     */
    public function yuanImg($picture) {
        $src_img = imagecreatefromstring(file_get_contents($picture));
        $w = imagesx($src_img);
        $h = imagesy($src_img);
        $w = min($w, $h);
        $h = $w;
        $img = imagecreatetruecolor($w, $h);
        //這一句必定要有
        imagesavealpha($img, true);
        //拾取一個徹底透明的顏色,最後一個參數127爲全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $w / 2; //圓半徑
        $y_x = $r; //圓心X座標
        $y_y = $r; //圓心Y座標
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        /**
         * 若是想要直接輸出圖片,應該先設header。header("Content-Type: image/png; charset=utf-8");
         * 而且去掉緩存區函數
         */
        //獲取輸出緩存,不然imagepng會把圖片輸出到瀏覽器
        ob_start();
        imagepng($img);
        imagedestroy($img);
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }

    /**
     * 在二維碼的中間區域鑲嵌圖片
     * @param $QR 二維碼數據流。好比file_get_contents(imageurl)返回的東東,或者微信給返回的東東
     * @param $logo 中間顯示圖片的數據流。好比file_get_contents(imageurl)返回的東東
     * @return  返回圖片數據流
     */
    public function qrcodeWithLogo($QR, $logo) {
        $QR = imagecreatefromstring($QR);
        $logo = imagecreatefromstring($logo);
        $QR_width = imagesx($QR); //二維碼圖片寬度
        $QR_height = imagesy($QR); //二維碼圖片高度
        $logo_width = imagesx($logo); //logo圖片寬度
        $logo_height = imagesy($logo); //logo圖片高度
        $logo_qr_width = $QR_width / 2.2; //組合以後logo的寬度(佔二維碼的1/2.2)
        $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);
        /**
         * 若是想要直接輸出圖片,應該先設header。header("Content-Type: image/png; charset=utf-8");
         * 而且去掉緩存區函數
         */
        //獲取輸出緩存,不然imagepng會把圖片輸出到瀏覽器
        ob_start();
        imagepng($QR);
        imagedestroy($QR);
        imagedestroy($logo);
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }

    /**
     * curl 請求
     * @param  [type] $url    [請求地址]
     * @param  string $data   [參數]
     * @param  string $method [請求方式]
     * @return [type]         [description]
     */
    public function httpRequest($url, $data = '', $method = 'GET') {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
}
date_default_timezone_set('PRC');
$a = new getMiniQrcode();
$id = $_GET['id'];
$a->index($id);                            

 

 

 

訪問該PHP文件  傳入 ?id=...php

 

 

 

 

1html

相關文章
相關標籤/搜索