<?php
/**
 * 生成海报
 * @Copyright (C) 2019 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Common\Vendor;
class Haibao{
    /**
     * 添加图片
     * @param $path_base    原图
     * @param $path_logo     添加图
     * @param $imgWidth     添加图宽
     * @param $imgHeight     添加图高
     * @param $dst_x         在原图宽x处添加
     * @param $dst_y         在原图高y处添加
     * @param $new             生成图
     * @return resource    返回图片image资源
     */
    public function addPic($path_base,$path_logo,$dst_x=0,$dst_y=0,$imgWidth=0,$imgHeight=0,$new=''){
        if(empty($path_base) || empty($path_logo))return false;
        if(!$new)$new=$path_base;
        $iinfo=getimagesize($path_logo);//取得添加图大小
        $x=$iinfo[0];$y=$iinfo[1];
        if(empty($imgWidth))$imgWidth=$x;
        if(empty($imgHeight))$imgHeight=$y;
        $image_base = $this->ImgInfo($path_base);
        $image_logo = $this->ImgInfo($path_logo);

        $yrate=$imgWidth/$imgHeight;$erate=$x/$y;
        if($yrate!=$erate){//如果图片和要写入的比例不一致则缩放
            if($x>$y){$x = $y*$yrate;/*图片宽大于高 横图*/} else {$y = $x/$yrate;}//图片高大于等于宽 竖图
        }
        imagecopyresampled($image_base, $image_logo, $dst_x, $dst_y, 0, 0,$imgWidth,$imgHeight,$x,$y);
        imagejpeg($image_base,$new);// 生成一个合并后的新图        
        return true;
    }
    /**
     * 添加多图片
     * @param $path_base    原图
     * @param $params     参数数组同上addPic
     * @param $new             生成图
     * @return resource    返回图片image资源
     */
    public function addPics($path_base,$params=array(),$new=''){
        if(empty($path_base) || empty($params))return false;
        if(!$new)$new=$path_base;
        $image_base = $this->ImgInfo($path_base);
        foreach($params as $v){
            @$path_logo=$v['path_logo'];$dst_x=$v['dst_x'];$dst_y=$v['dst_y'];$imgWidth=$v['imgWidth'];$imgHeight=$v['imgHeight'];
            if(empty($path_logo))continue;
            $iinfo=getimagesize($path_logo);//取得添加图大小
            $x=$iinfo[0];$y=$iinfo[1];
            if(empty($imgWidth))$imgWidth=$x;if(empty($imgHeight))$imgHeight=$y;
            $image_logo = $this->ImgInfo($path_logo);

            $yrate=$imgWidth/$imgHeight;$erate=$x/$y;
            if($yrate!=$erate){//如果图片和要写入的比例不一致则缩放
                if($x>$y){$x = $y*$yrate;/*图片宽大于高 横图*/} else {$y = $x/$yrate;}//图片高大于等于宽 竖图
            }
            imagecopyresampled($image_base, $image_logo, $dst_x, $dst_y, 0, 0,$imgWidth,$imgHeight,$x,$y);
        }
        imagejpeg($image_base,$new);// 生成一个合并后的新图        
        return true;
    }
    /**
     * 添加文字
     * @param $ori_img         生成图
     * @param $str        要添加的文字
     * @param $posX     在宽x处添加
     * @param $poxY     在高y处添加
     * @param $size     字体大小
     * @param $color     字体颜色 red black
     * @param $font     字体路径
     * @param $new_img  生成图
     * @return resource    返回图片image资源
     */
    public function addWord($ori_img,$str,$posX=0,$poxY=0,$size=0,$color='black',$font='',$new_img=''){
        if(empty($ori_img) || empty($str))return false;
        if(empty($new_img))$new_img=$ori_img;
        $s_original = $this->ImgInfo($ori_img);
        if(empty($font))$font = ROOT_PATH.'/Public/fonts/msyhbd.ttf'; //定义字体  
        if(!file_exists($font))$font='C:/Windows/Fonts/simfang.ttf';
        $tilt = 0;    //文字的倾斜度
        $ImgColor =$this->getcolor($color,$s_original);
        if(empty($size))$size = intval(C('FONT_SIZE'));
        if(empty($size))$size=20;
        if($str=='line'){
            imageline($s_original,$posX,$poxY,($posX+$size),$poxY,$ImgColor);
        }else{
            imagettftext($s_original, $size, $tilt, $posX, $poxY, $ImgColor,$font , $str);
        }
        $loop = imagejpeg($s_original, $new_img);    //生成新的图片(jpg格式)
        return true;
    }
    /**
     * 添加多行文字
     * @param $new        生成图
     * @param $params     参数数组同上addWord
     * @param $new_img  生成图
     * @return resource    返回图片image资源
     */
    public function addWords($ori_img,$params=array(),$new_img=''){
        if(empty($ori_img) || empty($params) || !is_array($params))return false;
        if(empty($new_img))$new_img=$ori_img;
        $s_original = $this->ImgInfo($ori_img);
        $tilt = 0;    //文字的倾斜度
        $ImgColor =$this->getcolor('all',$s_original);
        foreach($params as $v){
            @$font=$v['font'];$posX=$v['posX'];$poxY=$v['poxY'];@$color=$v['color'];$size=$v['size'];$str=$v['str'];
            if(empty($str))continue;
            if(empty($font))$font = ROOT_PATH.'/Public/fonts/msyhbd.ttf';if(!file_exists($font))$font='C:/Windows/Fonts/simfang.ttf'; //定义字体
            if(empty($size))$size = intval(C('FONT_SIZE'));if(empty($size))$size=20;//字号
            if(empty($color))$color='black';
            if($str=='line'){
                imageline($s_original,$posX,$poxY,($posX+$size),$poxY,$ImgColor[$color]);
            }else{
                imagettftext($s_original, $size, $tilt, $posX, $poxY, $ImgColor[$color],$font , $str);
            }
        }
        $loop = imagejpeg($s_original, $new_img);//生成新的图片(jpg格式)
        return true;
    }
    /**
     * 从图片文件创建Image资源
     * @param $file 图片文件，支持url
     * @return bool|resource    成功返回图片image资源，失败返回false
     */
    public function ImgInfo($img){
        if(preg_match('/http(s)?:\/\//',$img)){
            $fileSuffix = $this->getNetworkImgType($img);
        }else{
            $fileSuffix = pathinfo($img, PATHINFO_EXTENSION);
        }
        if(!$fileSuffix) return false;
        switch ($fileSuffix){
            case 'jpeg':$theImage = @imagecreatefromjpeg($img);break;
            case 'jpg':$theImage = @imagecreatefromjpeg($img);break;
            case 'png':$theImage = @imagecreatefrompng($img);break;
            case 'gif':$theImage = @imagecreatefromgif($img);break;
            default:$theImage = @imagecreatefromstring(file_get_contents($img));break;
        }
        return $theImage;
    }
    /**
     * 获取网络图片类型
     * @param $url  网络图片url,支持不带后缀名url
     * @return bool
     */
    private function getNetworkImgType($url){
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url); //设置需要获取的URL
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);//设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //支持https
        curl_exec($ch);//执行curl会话
        $http_code = curl_getinfo($ch);//获取curl连接资源句柄信息
        curl_close($ch);//关闭资源连接
        if ($http_code['http_code'] == 200) {
            $theImgType = explode('/',$http_code['content_type']);
            if($theImgType[0] == 'image'){
                return $theImgType[1];
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    /**
     * 分行连续截取字符串
     * @param $str  需要截取的字符串,UTF-8
     * @param int $row  截取的行数
     * @param int $number   每行截取的字数，中文长度
     * @param bool $suffix  最后行是否添加‘...’后缀
     * @return array    返回数组共$row个元素，下标1到$row
     */
    public function cn_row_substr($str,$row = 1,$number = 10,$suffix = true){
        $result = array();
        for ($r=1;$r<=$row;$r++){$result[$r] = '';}
        $str = trim($str);
        if(!$str) return $result;
        $theStrlen = strlen($str);
        //每行实际字节长度
        $oneRowNum = $number * 3;
        for($r=1;$r<=$row;$r++){
            if($r == $row and $theStrlen > $r * $oneRowNum and $suffix){
                $result[$r] = $this->mg_cn_substr($str,$oneRowNum-6,($r-1)* $oneRowNum).'...';
            }else{
                $result[$r] = $this->mg_cn_substr($str,$oneRowNum,($r-1)* $oneRowNum);
            }
            if($theStrlen < $r * $oneRowNum) break;
        }
        return $result;
    }
    /**
     * 获取居中坐标
     * @param $str
     * @param $size字号
     * @param $width 整个大图的宽度
     */
    public function getcenterx($str,$size=20,$width=720,$font=''){
        $length= $this->checkStrlength($str,$size,$font);
        return  floor(($width - $length)/2);
    }
    /**
     * 计算字符串的宽度
     * @param $str 要计算的字符串
     * @param $size 字体大小
     * @param $font 字体路径
     */
    public function checkStrlength($str,$size=20,$font=''){
        if(empty($font))$font=ROOT_PATH.'/Public/fonts/msyhbd.ttf';
        $rect =imagettfbbox($size, 0,$font , $str);
        $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
        $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
        $length=$maxX-$minX;
        return $length;
    }
    private function format_num($num=''){
        if(empty($num) && !is_numeric($num))return 'auto';
        return intval($num).'rpx';
    }
    private function format_url($url='',$is_https=true){
        $url=format_url($url);
        return $is_https?str_replace('http://','https://',$url):$url;
    }
    /**
     * 格式化成小程序生成海报可用数组
     * @param $array 同上批量添加文本及图片结构
     * @param $poster 海报基本配置参数
     * @return array https://github.com/Kujiale-Mobile/Painter
     */
    public function format_mini($array,$poster=array()){
        $dataList=array();
        $background=$poster['background'];$width=$poster['width'];$height=$poster['height'];
        if(empty($background) || substr($background,0,1)=='#'){
            $dataList['background']=$background?$background:'#ffffff';
        }else{
            if(empty($background))return $dataList;
            if(empty($width) || empty($height)){$size =$this->getimgsize($background);$width=$size[0]?$size[0]:720;$height=$size[1]?$size[1]:1280;}
            $dataList['background']=$this->format_url($poster['background']);
        }
        $dataList['width']=$this->format_num($width);
        $dataList['height']=$this->format_num($height);

        $content=array();
        foreach($array as $v){
            $css=array();
            if(!empty($v['str'])){//文字
                if($v['str']=='rect') {//形状
                    $view['type']= 'rect';
                }else{
                    $view['type']= 'text';
                    $css['fontSize']= $this->format_num($v['size']);
                    $view['text']= $v['str'];
                }

                $ImgColor =str_exists($v['color'],'#')?$v['color']:$this->getcolor($v['color']);
                $css['left']= $this->format_num($v['posX']);
                $css['top']= $this->format_num($v['poxY']);
                $css['color']= $ImgColor;
                if(!empty($v['textDecoration']))$css['textDecoration']= $v['textDecoration'];
                if(!empty($v['fontWeight']))$css['fontWeight']= $v['fontWeight'];
                if(!empty($v['maxLines']))$css['maxLines']= $v['maxLines'];
                if(!empty($v['width']))$css['width']= $this->format_num($v['width']);
                if(!empty($v['height']))$css['height']= $this->format_num($v['height']);
                if(!empty($v['textAlign']))$css['textAlign']= $v['textAlign'];
                if(!empty($v['padding']))$css['padding']= $v['padding'];
                if(!empty($v['background']))$css['background']= $v['background'];
                if(!empty($v['textStyle']))$css['textStyle']= $v['textStyle'];
                if(!empty($v['shadow']))$css['shadow']= $v['shadow'];//阴影
                $view['css']=$css;
                $content[]=$view;
            }
            if(!empty($v['path_logo'])){//图片
                $css['left']= $this->format_num($v['dst_x']);
                $css['top']= $this->format_num($v['dst_y']);
                $css['width']= $this->format_num($v['imgWidth']);
                $css['height']= $this->format_num($v['imgHeight']);

                if(!empty($v['shadow']))$css['shadow']= $v['shadow'];//阴影
                if(!empty($v['rotate']))$css['rotate']= $v['rotate'];//旋转，按照顺时针旋转的度数
                if(!empty($v['borderRadius']))$css['borderRadius']= $v['borderRadius'];//设置圆角
                $content[]=array('type'=> 'image','url'=> $this->format_url($v['path_logo']),'css'=>$css);
            }
        }
        $dataList['views']=$content;
        return $dataList;
    }
    public function getcolor($color='',$s_original=''){
        if($s_original){
            $ImgColor = array(                    //为一幅图像分配颜色 
                'black' => imagecolorallocate($s_original,0,0,0),
                'red' => imagecolorallocate($s_original,255,0,0),
                'orange' => imagecolorallocate($s_original,252, 117, 0),
                'white' => imagecolorallocate($s_original,255,255,255),
                'gray' => imagecolorallocate($s_original,182,182,182),
                '#55bd47'=>imagecolorallocate($s_original,85,189,71),
                '#10ad61'=>imagecolorallocate($s_original,16,173,97),
                '#35a4de'=>imagecolorallocate($s_original,53,164,222),
                '#3d78da'=>imagecolorallocate($s_original,61,120,218),
                '#9058cb'=>imagecolorallocate($s_original,144,88,203),
                '#de9c33'=>imagecolorallocate($s_original,222,156,51),
                '#ebac16'=>imagecolorallocate($s_original,235,172,22),
                '#f9861f'=>imagecolorallocate($s_original,249,134,31),
                '#e75735'=>imagecolorallocate($s_original,231,87,53),
                '#d54036'=>imagecolorallocate($s_original,213,64,54),
                '#cf3e36'=>imagecolorallocate($s_original,207,62,54),
                '#ffffff'=>imagecolorallocate($s_original,255,255,255),
                '#000000'=>imagecolorallocate($s_original,0,0,0),
            );
        }else{
            $ImgColor = array(                    //为一幅图像分配颜色 
                'black' => '#000',
                'red' => '#f00',
                'orange' => '#FC7500',
                'white' => '#fff',
                'gray' => '#B6B6B6',
            );
            if(substr($color,0,1)=='#')$ImgColor[$color]=$color;
        }
        if($color=='all')return $ImgColor;
        return $color && $ImgColor[$color]?$ImgColor[$color]:$ImgColor['orange'];
    }
    public function getimgsize($img){
        $img=format_url($img,2);
        if(substr($img,0,4)=='http'){
            $cache=S($img);if($cache)return $cache;
            $ch = curl_init($img);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            // 取前面 168 个字符 通过四张测试图读取宽高结果都没有问题,若获取不到数据可适当加大数值  
            curl_setopt($ch, CURLOPT_RANGE, '0-167');
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $dataBlock = curl_exec($ch);
            curl_close($ch);
            $size = getimagesize('data://image/jpeg;base64,'. base64_encode($dataBlock));
            S($img,$size);
        }else{
            $size =getimagesize($img);
        }
        return $size;
    }
    /**
     * 按字节截取utf-8字符串
     * 识别汉字全角符号，全角中文3个字节，半角英文1个字节
     * @param $str  需要切取的字符串
     * @param $len  截取长度[字节]
     * @param int $start    截取开始位置，默认0
     * @return string
     */
    private function mg_cn_substr($str,$len,$start = 0){
        $q_str = '';
        $q_strlen = ($start + $len)>strlen($str) ? strlen($str) : ($start + $len);
        //如果start不为起始位置，若起始位置为乱码就按照UTF-8编码获取新start
        if($start and json_encode(substr($str,$start,1)) === false){
            for($a=0;$a<3;$a++){
                $new_start = $start + $a;
                $m_str = substr($str,$new_start,3);
                if(json_encode($m_str) !== false) {$start = $new_start;break;}
            }
        }
        //切取内容
        for($i=$start;$i<$q_strlen;$i++){
            //ord()函数取得substr()的第一个字符的ASCII码，如果大于0xa0的话则是中文字符
            if(ord(substr($str,$i,1))>0xa0){
                $q_str .= substr($str,$i,3);
                $i+=2;
            }else{
                $q_str .= substr($str,$i,1);
            }
        }
        return $q_str;
    }
}
?>