PHP 生成自定義海報,自定義二維碼

前言:關(guān)于php生成自定義海報,網(wǎng)上的教程一搜一大片,但是當(dāng)你真正用到的時候,似乎沒有一個好使的,這樣致使生成海報一直是我的一個難點(diǎn),我也懶得時間去搞這些東西,然后時間一拖就拖了兩年,今年客戶有類似的需求,想著今天就整理整理吧

  1. 生成海報首先要明白他是怎么生成的,其實(shí)很簡單,就是用畫布把多張圖片組合起來,然后在和背景圖組合起來就生成海報了,所以您有必要了解一下必知的畫布函數(shù)
  • imagecreatetruecolor 創(chuàng)建背景畫布
  • imagecreatefromstring 創(chuàng)建一個圖像資源從字符串中的圖像流。

擴(kuò)展
imagecreate — 新建一個基于調(diào)色板的圖像

imagecreatetruecolor — 新建一個真彩色圖像

imagecreatefromstring — 創(chuàng)建一個圖像資源從字符串中的圖像流。

$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
      . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
      . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
      . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
   header('Content-Type: image/png');
   imagepng($im);
}
else {
   echo 'An error occured.';
}
  • imagecopy將圖片繪制到畫布上http://www.5idev.com/p-php_imagecopy_imagecopyresized.shtml
  • imagedestroy釋放與關(guān)聯(lián)圖片的內(nèi)存
  • imagesx imagesy獲取頭像的寬高
  • imagecopyresized拷貝圖片
  • imagecolorallocate()設(shè)置圖像顏色,多用于繪制文字的顏色
  • imagettftext繪制文字
  • imagepng輸出圖像
  1. 然后第二步我們就需要用到一個插件phpqrcode
    關(guān)于phpqrcode其實(shí)就是php生成二維碼的一個插件,方便快捷
require_once IA_ROOT . '/framework/library/qrcode/phpqrcode.php';
首先我們先用phpqrcode做一個生成二維碼的方法接口
public function createQrcode($mid = 0, $posterid = 0)
    {
        global $_W;
        global $_GPC;
        $path = IA_ROOT . '/addons/ewei_shopv2/data/qrcode/' . $_W['uniacid'] . '/';

        if (!is_dir($path)) {
            load()->func('file');
            mkdirs($path);
        }

        $url = mobileUrl('', array('mid' => $mid), true);

        if (!empty($posterid)) {
            $url .= '&posterid=' . $posterid;
        }

        $file = 'shop_qrcode_' . $posterid . '_' . $mid . '.png';
        $qrcode_file = $path . $file;

        if (!is_file($qrcode_file)) {
            require_once IA_ROOT . '/framework/library/qrcode/phpqrcode.php';
            QRcode::png($url, $qrcode_file, QR_ECLEVEL_L, 4);
        }

        return $_W['siteroot'] . 'addons/ewei_shopv2/data/qrcode/' . $_W['uniacid'] . '/' . $file;
    }
第二步調(diào)用上面的接口生成一個可以掃描的二維碼,然后下面做背景圖,字合成,然后也是先寫一個接口,方面咱們后期直接復(fù)制使用
  • 創(chuàng)建圖片(圖片流,比如base64轉(zhuǎn)換)
public function createImage($imgurl)
    {
        load()->func('communication');
        $resp = ihttp_request($imgurl);
        if ($resp['code'] == 200 && !empty($resp['content'])) {
            return imagecreatefromstring($resp['content']);
        }

        $i = 0;

        while ($i < 3) {
            $resp = ihttp_request($imgurl);
            if ($resp['code'] == 200 && !empty($resp['content'])) {
                return imagecreatefromstring($resp['content']);
            }

            ++$i;
        }

        return '';
    }
  • 處理圖像px
public function getRealData($data)
    {
        $data['left'] = intval(str_replace('px', '', $data['left'])) * 2;
        $data['top'] = intval(str_replace('px', '', $data['top'])) * 2;
        $data['width'] = intval(str_replace('px', '', $data['width'])) * 2;
        $data['height'] = intval(str_replace('px', '', $data['height'])) * 2;
        $data['size'] = intval(str_replace('px', '', $data['size'])) * 2;
        $data['src'] = tomedia($data['src']);
        return $data;
    }
  • 拷貝圖片和制作文字的接口
public function mergeImage($target, $data, $imgurl)
    {
        $img = $this->createImage($imgurl);
        $w = imagesx($img);
        $h = imagesy($img);
        imagecopyresized($target, $img, $data['left'], $data['top'], 0, 0, $data['width'], $data['height'], $w, $h);
        imagedestroy($img);
        return $target;
    }
    
    public function mergeText($target, $data, $text)
    {
        $font = IA_ROOT . '/addons/ewei_shopv2/static/fonts/msyh.ttf';
        $colors = $this->hex2rgb($data['color']);
        $color = imagecolorallocate($target, $colors['red'], $colors['green'], $colors['blue']);
        imagettftext($target, $data['size'], 0, $data['left'], $data['top'] + $data['size'], $color, $font, $text);
        return $target;
    }
  • 上傳圖片
public function uploadImage($img)
    {
        load()->func('communication');
        $account = m('common')->getAccount();
        $access_token = $account->fetch_token();
        $url = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image';
        $ch1 = curl_init();
        $data = array('media' => '@' . $img);

        if (version_compare(PHP_VERSION, '5.5.0', '>')) {
            $data = array('media' => curl_file_create($img));
        }

        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
        $content = @json_decode(curl_exec($ch1), true);

        if (!is_array($content)) {
            $content = array('media_id' => '');
        }

        curl_close($ch1);
        return $content['media_id'];
    }

總,然后調(diào)用接口

    
    public function createPoster($poster, $member, $qr, $upload = true)
    {
        //$poster  海報信息   $qr 二維碼
        global $_W;
        $path = IA_ROOT . '/addons/ewei_shopv2/data/poster/' . $_W['uniacid'] . '/';

        if (!is_dir($path)) {
            load()->func('file');
            mkdirs($path);
        }

    
        $md5 = md5(json_encode(array('siteroot' => $_W['siteroot'], 'openid' => $member['openid'], 'goodsid' => $qr['goodsid'], 'bg' => $poster['bg'], 'data' => $poster['data'], 'version' => 1)));
        
        $file = $md5 . '.png';
        
        
        if (!is_file($path . $file) || $qr['qrimg'] != $qr['current_qrimg']) {
            //突破256M的限制
            set_time_limit(0);
            @ini_set('memory_limit', '256M');
            
            $target = imagecreatetruecolor(640, 1008);
            
            $bg = $this->createImage(tomedia($poster['bg']));
            imagecopy($target, $bg, 0, 0, 0, 0, 640, 1008);
            imagedestroy($bg);
            $data = json_decode(str_replace('&quot;', '\'', $poster['data']), true);

            foreach ($data as $d) {
                $d = $this->getRealData($d);

                if ($d['type'] == 'head') {
                    $avatar = preg_replace('/\\/0$/i', '/96', $member['avatar']);
                    $target = $this->mergeImage($target, $d, $avatar);
                }
                else if ($d['type'] == 'img') {
                    $target = $this->mergeImage($target, $d, $d['src']);
                }
                else if ($d['type'] == 'qr') {
                    $target = $this->mergeImage($target, $d, tomedia($qr['current_qrimg']));
                }
                else if ($d['type'] == 'nickname') {
                    $target = $this->mergeText($target, $d, $member['nickname']);
                }
                else {
                    if (!empty($goods)) {
                        if ($d['type'] == 'title') {
                            $title_width = (int) ($d['width'] / $d['size'] / 1.2);
                            $width_left = 0;

                            while ($width_left < strlen($goods['title'])) {
                                $title = mb_substr($goods['title'], $width_left, $title_width, 'utf-8');
                                $width_left += $title_width;
                                $d['top'] += $d['size'] * 2;
                                $target = $this->mergeText($target, $d, $title);
                            }
                        }
                        else if ($d['type'] == 'thumb') {
                            $thumb = !empty($goods['commission_thumb']) ? tomedia($goods['commission_thumb']) : tomedia($goods['thumb']);
                            $target = $this->mergeImage($target, $d, $thumb);
                        }
                        else if ($d['type'] == 'marketprice') {
                            $target = $this->mergeText($target, $d, $goods['marketprice']);
                        }
                        else {
                            if ($d['type'] == 'productprice') {
                                $target = $this->mergeText($target, $d, $goods['productprice']);
                            }
                        }
                    }
                }
            }

            imagepng($target, $path . $file);
            imagedestroy($target);

            if ($qr['qrimg'] != $qr['current_qrimg']) {
                pdo_update('ewei_shop_poster_qr', array('qrimg' => $qr['current_qrimg']), array('id' => $qr['id']));
            }
        }

        $img = $_W['siteroot'] . 'addons/ewei_shopv2/data/poster/' . $_W['uniacid'] . '/' . $file;

        if (!$upload) {
            return $img;
        }

        if ($qr['qrimg'] != $qr['current_qrimg'] || empty($qr['mediaid']) || empty($qr['createtime']) || $qr['createtime'] + 3600 * 24 * 3 - 7200 < time()) {
            $mediaid = $this->uploadImage($path . $file);
            $qr['mediaid'] = $mediaid;
            pdo_update('ewei_shop_poster_qr', array('mediaid' => $mediaid, 'createtime' => time()), array('id' => $qr['id']));
        }

        return array('img' => $img, 'mediaid' => $qr['mediaid']);
    }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 創(chuàng)建圖像小案例 簡單驗(yàn)證碼 第一步 生成一個隨機(jī)數(shù) <?php //第一步設(shè)置mime類型,輸出類型 ///hea...
    周行知閱讀 205評論 0 0
  • GD庫簡介 GD指的是Graphic Device,PHP的GD庫是用來處理圖形的擴(kuò)展庫,通過GD庫提供的一系列A...
    敬業(yè)福閱讀 792評論 0 0
  • 接著昨天沒寫完的故事來! 夏天到了,雖然天氣炎熱,酷暑難耐,但卻是我們這個五金行業(yè)的旺季。為了爭取在旺季多賺點(diǎn)錢,...
    ld熊壯壯閱讀 288評論 0 0
  • 轉(zhuǎn)眼間八月也慌慌張張的來了,在武漢兜兜轉(zhuǎn)轉(zhuǎn)也呆了近一個月了。從一開始的一個人住的惶恐不安,到后來與宿舍的阿姨姐姐們...
    蚪蚪_d27f閱讀 474評論 2 1
  • 在閱讀完property_t相關(guān)代碼之后,接下來學(xué)習(xí)和property_t十分相似的內(nèi)容Ivar,我們就不再去做一...
    zevwings閱讀 913評論 0 1

友情鏈接更多精彩內(nèi)容