PHP 生成自定义海报,自定义二维码

目 录

前言:关于php生成自定义海报,网上的教程一搜一大片,但是当你真正用到的时候,似乎没有一个好使的,这样致使生成海报一直是我的一个难点,我也懒得时间去搞这些东西,然后时间一拖就拖了两年,今年客户有类似的需求,想着今天就整理整理吧

  1. 生成海报首先要明白他是怎么生成的,其实很简单,就是用画布把多张图片组合起来,然后在和背景图组合起来就生成海报了,所以您有必要了解一下必知的画布函数
  • imagecreatetruecolor 创建背景画布
  • imagecreatefromstring 创建一个图像资源从字符串中的图像流。

扩展
imagecreate — 新建一个基于调色板的图像

imagecreatetruecolor — 新建一个真彩色图像

imagecreatefromstring — 创建一个图像资源从字符串中的图像流。

$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释放与关联图片的内存
  • imagesx imagesy获取头像的宽高
  • imagecopyresized拷贝图片
  • imagecolorallocate()设置图像颜色,多用于绘制文字的颜色
  • imagettftext绘制文字
  • imagepng输出图像
  1. 然后第二步我们就需要用到一个插件phpqrcode
    关于phpqrcode其实就是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;
    }
第二步调用上面的接口生成一个可以扫描的二维码,然后下面做背景图,字合成,然后也是先写一个接口,方面咱们后期直接复制使用
  • 创建图片(图片流,比如base64转换)

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'];
    }

总,然后调用接口

    
    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']);
    }

0人点赞

常见问题FAQ

免费下载或者VIP会员专享资源能否直接商用?
本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
幕鹿源码小姐姐亲测微擎源码,支持二次开发哦,加入会员免费修复bug,任何会员无限下载全站内容
微擎二开-社区团购|人人商城|禾匠商城|啦啦外卖|智慧同城 » PHP 生成自定义海报,自定义二维码
493+

本站勉强运行

175+

用户总数

321+

资源总数

2+

今日更新

2020-7-2

最后更新时间


keywords:人人商城 人人商城