欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

thinkphp 利用GD库在图片上写文字

程序员文章站 2022-04-14 15:37:23
调用方法: ......


<?php /** * created by phpstorm. * user: administrator */ namespace home\event; use \think\image; use \think\upload; class imgevent { private $think_image = null; private $think_upload = null; public function __construct() { $this->think_image = new image(); $this->think_upload = new upload(); } /* * 保存base64文件 * $img string base64类型的文件 * $type string 保存的文件类型 * app_user_head_img 用户头像 * * */ public function saveimg_base64($img = null , $type = null) { //获取保存图片配置 $imgconfig_savepath = c("img_save.save_path"); $imgconfig_size = c("img_save.size"); $saveflag = false; // dump($imgconfig_savepath[$type]); // dump($imgconfig_size); if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result) && $imgconfig_savepath[$type]) { $img_ext = $result[2]; //图片后缀 $img_header = $result[1];//图片头信息 $new_file_name = date('ymd').'/'.uniqid().'.'.$img_ext; $origin_img_path = '';//原图的保存路径 $origin_img_save_flag = true;// foreach($imgconfig_savepath[$type] as $k => $v) { if(!is_dir($v.date('ymd'))) { mkdir($v.date('ymd'),0777,true); } if ($k == 'origin') { //先保存一份原图,然后其他尺寸的保存直接调用原图路径origin_img_path. $origin_res = file_put_contents($v.$new_file_name, base64_decode(str_replace($img_header, '', $img))); if (!$origin_res) { $origin_img_save_flag = false; break; } else { $saveflag = $new_file_name; $origin_img_path = $v.$new_file_name; $this->think_image->open($origin_img_path); } } else { if ($origin_img_save_flag) { $width = $imgconfig_size[$type][$k]['w']; $height = $imgconfig_size[$type][$k]['h']; $this->think_image->thumb($width, $height,3)->save($v.$new_file_name); } } } } return $saveflag; } /* * 保存file类型文件 * */ public function saveimg_file($img = null , $type = null) { //获取保存图片配置 $imgconfig_savepath = c("img_save.save_path"); $imgconfig_size = c("img_save.size"); $saveflag = false; if ($img && $imgconfig_savepath[$type]) { $origin_img_save_flag = true; foreach($imgconfig_savepath[$type] as $k => $v) { if(!is_dir($v.date('ymd'))) { mkdir($v.date('ymd'),0777,true); } if ($k == 'origin') { $this->think_upload->rootpath = $v; $this->think_upload->subname = date('ymd'); $this->think_upload->savename = array('uniqid',''); $saveres = $this->think_upload->uploadone($img); if (!$saveres) { $origin_img_save_flag = false; } else { $saveflag = true; $origin_img_path = $v.$saveres['savepath'].$saveres['savename']; $this->think_image->open($origin_img_path); $filename = $saveres['savepath'].$saveres['savename']; } } else { if ($origin_img_save_flag) { $width = $imgconfig_size[$type][$k]['w']; $height = $imgconfig_size[$type][$k]['h']; $compress_img_path=$v.$filename; $saveflag = $this->think_image->thumb($width, $height,3)->save($v.$filename); if (!$saveflag) { $saveflag = false; $origin_img_save_flag = false; } } } } if($saveflag) { #$saveflag = $filename; $saveflag = array('origin'=>get_current_host().'/'.$origin_img_path,'compress'=>get_current_host().'/'.$compress_img_path); } } return $saveflag; } public function save_file($img = null , $type = null) { //获取保存图片配置 $imgconfig_savepath = c("img_save.save_path"); $saveflag = false; if ($img && $imgconfig_savepath[$type]) { if (!is_dir($imgconfig_savepath[$type] . date('ymd'))) { mkdir($imgconfig_savepath[$type] . date('ymd'), 0777, true); } $this->think_upload->rootpath = $imgconfig_savepath[$type]; $this->think_upload->subname = date('ymd'); $this->think_upload->savename = array('uniqid', ''); $saveres = $this->think_upload->uploadone($img); if ($saveres) { $saveflag = true; $origin_img_path = $imgconfig_savepath[$type] . $saveres['savepath'] . $saveres['savename']; //$filename = $saveres['savepath'] . $saveres['savename']; } } if($saveflag) { $saveflag = $origin_img_path; return get_current_host().'/'.$saveflag; }else { return $saveflag; } } /* * 保存file类型文件,多文件 * */ public function saveimgs_files($imgs = null , $type = null) { //获取保存图片配置s $imgconfig_savepath = c("img_save.save_path"); $imgconfig_size = c("img_save.size"); $saveflag = false; $imgresarr = array();//保存图片路径 $origin_img_path = array();//原图路径 if ($imgs && $imgconfig_savepath[$type]) { $origin_img_save_flag = true; foreach($imgconfig_savepath[$type] as $k => $v) { if(!is_dir($v.date('ymd'))) { mkdir($v.date('ymd'),0777,true); } if ($k == 'origin') { $this->think_upload->rootpath = $v; $this->think_upload->subname = date('ymd'); $this->think_upload->savename = array('uniqid',''); $saveres = $this->think_upload->upload($imgs); if ($saveres) { $saveflag = true; foreach ($saveres as $srk => $srv) { $origin_img_path[] = $v.$saveres[$srk]['savepath'].$saveres[$srk]['savename']; $filename = $saveres[$srk]['savepath'].$saveres[$srk]['savename']; $imgresarr[] = $filename; } } } else { foreach($origin_img_path as $oipk => $oipv) { if ($saveflag) { $width = $imgconfig_size[$type][$k]['w']; $height = $imgconfig_size[$type][$k]['h']; $this->think_image->open($oipv); $savethumb = $this->think_image->thumb($width, $height,3)->save($v.$imgresarr[$oipk]); if (!$savethumb) { $saveflag = false; break; } } } } } if ($saveflag) { $saveflag = $imgresarr; } } return $saveflag; } /* * 保存微信头像 - url * */ public function save_wximg($picurl = '',$type = null) { $ch = curl_init($picurl); curl_setopt($ch, curlopt_header, 0); curl_setopt($ch, curlopt_nobody, 0); //对body进行输出。 curl_setopt($ch, curlopt_returntransfer, 1); $package = curl_exec($ch); $httpinfo = curl_getinfo($ch); curl_close($ch); $media = array_merge(array('mediabody' => $package), $httpinfo); //求出文件格式 preg_match('/\w\/(\w+)/i', $media["content_type"], $extmatches); $fileext = $extmatches[1]; $savename = md5(microtime(true)).".{$fileext}"; //获取保存图片配置 $imgconfig_savepath = c("img_save.save_path"); $imgconfig_size = c("img_save.size"); $saveflag = false; if ($imgconfig_savepath[$type]) { $origin_img_save_flag = true; foreach($imgconfig_savepath[$type] as $k => $v) { if(!is_dir($v.date('ymd'))) { mkdir($v.date('ymd'),0777,true); } if ($k == 'origin') { file_put_contents($v.'/'.date('ymd').'/'.$savename,$media['mediabody']); $origin_img_path = $v.'/'.date('ymd').'/'.$savename; $this->think_image->open($origin_img_path); $filename = date('ymd').'/'.$savename; } else { if ($origin_img_save_flag) { $width = $imgconfig_size[$type][$k]['w']; $height = $imgconfig_size[$type][$k]['h']; $saveflag = $this->think_image->thumb($width, $height,3)->save($v.$filename); if (!$saveflag) { $saveflag = false; $origin_img_save_flag = false; } else { $saveflag = $filename; } } } } } return $saveflag; } /* * 保存file类型文件 * */ public function saveimg_wx($wximg = array() , $type = null) { //获取保存图片配置 $imgconfig_savepath = c("img_save.save_path"); $imgconfig_size = c("img_save.size"); $saveflag = false; $imgresarr = array(); if ($wximg && $imgconfig_savepath[$type]) { foreach ($wximg as $wik => $wiv) { $wximg = $this->getwximg($wiv); $origin_img_save_flag = true; foreach($imgconfig_savepath[$type] as $k => $v) { if(!is_dir($v.date('ymd'))) { mkdir($v.date('ymd'),0777,true); } if ($k == 'origin') { file_put_contents($v.'/'.date('ymd').'/'.$wximg['savename'],$wximg['imgmedia']['mediabody']); $origin_img_path = $v.'/'.date('ymd').'/'.$wximg['savename']; $this->think_image->open($origin_img_path); $filename = date('ymd').'/'.$wximg['savename']; $imgresarr[] = $filename; } else { if ($origin_img_save_flag) { $width = $imgconfig_size[$type][$k]['w']; $height = $imgconfig_size[$type][$k]['h']; $saveflag = $this->think_image->thumb($width, $height,3)->save($v.$filename); if (!$saveflag) { $saveflag = false; $origin_img_save_flag = false; } else { $saveflag = $filename; } } } } } if($saveflag) { $saveflag = $imgresarr; } } return $saveflag; }    /* * 保存用户的推广图片 在图片上写字!!!! */ public function save_usershareimg($bg_img_path = '' , $head_img_path = '' , $qrcode_img_path = '' , $savefile = '' , $username = '' , $userdscp = '' , $font_path = '') { //设置头像图片为圆角 $head_img_radius = $this->radius_img($head_img_path,240); //合并到背景图中 $this->mergeimage($bg_img_path,$head_img_radius,$savefile,array('left' => 200, 'top' => 55, 'width' => 480, 'height' => 480)); //设置名称 $this->writetext($savefile, $savefile, $username,255,255,255,1010,32,$font_path, array()); //设置二维码内容 $this->mergeimage($savefile,$qrcode_img_path,$savefile,array('left' => 255, 'top' => 684, 'width' => 250, 'height' => 245)); return $savefile; } /* * 合并图片 */ private function mergeimage($bg_img, $main_img, $savefile, $param) { extract($param); // list($bgwidth, $bgheight) = getimagesize($bg_img); $bgimg = $this->imagecreate($bg_img); if (!is_resource($main_img)) { list($mainwidth, $mainheight) = getimagesize($main_img); $mainimg = $this->imagecreate($main_img); } else { $mainimg = $main_img; $mainwidth = $width; $mainheight = $height; } imagecopyresized($bgimg, $mainimg, $left, $top, 0, 0, $width, $height, $mainwidth, $mainheight); // imagecopyresized($bgimg, $mainimg, $left, $top, 0, 0, $width, $height, $width,$height); ob_start(); // output jpeg (or any other chosen) format & quality imagejpeg($bgimg, null, 100); $contents = ob_get_contents(); ob_end_clean(); imagedestroy($bgimg); imagedestroy($mainimg); $fh = fopen($savefile, "w+"); fwrite($fh, $contents); fclose($fh); } /* * 图片写文字 * $bg_img 背景图片 * $savefile 保存图片路径 * $text 文字 * $fontcolor 字体颜色 * $top 图片距离顶端高度 * $fontsize 字体大小 * $font 字体路径 * $param 传递的参数 */ private function writetext($bg_img, $savefile, $text, $colorr,$colorg,$colorb , $top , $fontsize , $font , $param = array()) { list($bgwidth, $bgheight) = getimagesize($bg_img); $im = imagecreatefromjpeg($bg_img); $fontcolor = imagecolorallocate($im, $colorr, $colorg, $colorb);//字的rgb颜色 $str = mb_convert_encoding($text, "html-entities", "utf-8");;//解决乱码问题 $fontbox = imagettfbbox($fontsize, 0, $font, $str);//文字水平居中实质 $width = imagesx($im); imagettftext($im, $fontsize, 0, ceil(($width - $fontbox[2]) / 2), $top, $fontcolor, $font, $str); ob_start(); // output jpeg (or any other chosen) format & quality imagejpeg($im, null, 100); $contents = ob_get_contents(); ob_end_clean(); imagedestroy($im); $fh = fopen($savefile, "w+"); fwrite($fh, $contents); fclose($fh); } /** * 处理圆角图片 * @param string $imgpath 源图片路径 * @param integer $radius 圆角半径长度默认为15,处理成圆型 * @return [type] [description] */ public function radius_img($imgpath = '', $radius = 65) { $ext = pathinfo($imgpath); $src_img = null; switch ($ext['extension']) { case 'jpg': $src_img = imagecreatefromjpeg($imgpath); break; case 'png': $src_img = imagecreatefrompng($imgpath); break; default: $src_img = imagecreatefromjpeg($imgpath); break; } $wh = getimagesize($imgpath); $w = $wh[0]; $h = $wh[1]; // $radius = $radius == 0 ? (min($w, $h) / 2) : $radius; $img = imagecreatetruecolor($w, $h); //这一句一定要有 imagesavealpha($img, true); //拾取一个完全透明的颜色,最后一个参数127为全透明 $bg = imagecolorallocatealpha($img, 255, 255, 255, 127); imagefill($img, 0, 0, $bg); $r = $radius; //圆 角半径 for ($x = 0; $x < $w; $x++) { for ($y = 0; $y < $h; $y++) { $rgbcolor = imagecolorat($src_img, $x, $y); if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) { //不在四角的范围内,直接画 imagesetpixel($img, $x, $y, $rgbcolor); } else { //在四角的范围内选择画 //上左 $y_x = $r; //圆心x坐标 $y_y = $r; //圆心y坐标 if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) { imagesetpixel($img, $x, $y, $rgbcolor); } //上右 $y_x = $w - $r; //圆心x坐标 $y_y = $r; //圆心y坐标 if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) { imagesetpixel($img, $x, $y, $rgbcolor); } //下左 $y_x = $r; //圆心x坐标 $y_y = $h - $r; //圆心y坐标 if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) { imagesetpixel($img, $x, $y, $rgbcolor); } //下右 $y_x = $w - $r; //圆心x坐标 $y_y = $h - $r; //圆心y坐标 if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) { imagesetpixel($img, $x, $y, $rgbcolor); } } } } return $img; } private function imagecreate($bg) { $bgimg = @imagecreatefromjpeg($bg); if (false == $bgimg) { $bgimg = @imagecreatefrompng($bg); } if (false == $bgimg) { $bgimg = @imagecreatefromgif($bg); } return $bgimg; } /* * 下载微信服务器的图片 * media_id 微信的媒体id * type 保存图片类型 * */ public function getwximg($mediaid) { if(!class_exists('\jssdk') && !class_exists('\wxpayconfig')) { vendor('wxsdkapi.jssdk'); vendor('wxpayapi.lib.wxpay#config'); } $res = new \jssdk(c('weixinpay_config.appid'),c('weixinpay_config.appsecret')); $accesstoken = $res->getaccesstoken(); // $mediaid = 'cvqpihdppthutayzs27gk6rn4-dsea6azntjxcg7_vaeuaakcl53x32hmkxhgisd'; // $accesstoken = 'khaopjy444kj06lch9esj-73pkefftgir3l45ruruuxv1ktjgxyfepj-ctif_ouyakyyb5dk2r9l_wc-wdw2usqgqbmobc6dzpimuhpqxb8jxz41culdtjiaezk8vf5kwssjaaaaww'; $picurl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$accesstoken&media_id=$mediaid"; $ch = curl_init($picurl); curl_setopt($ch, curlopt_header, 0); curl_setopt($ch, curlopt_nobody, 0); //对body进行输出。 curl_setopt($ch, curlopt_returntransfer, 1); $package = curl_exec($ch); $httpinfo = curl_getinfo($ch); curl_close($ch); $media = array_merge(array('mediabody' => $package), $httpinfo); //求出文件格式 preg_match('/\w\/(\w+)/i', $media["content_type"], $extmatches); $fileext = $extmatches[1]; $savename = md5(microtime(true)).".{$fileext}"; $img = array('imgmedia'=>$media,'savename'=>$savename); return $img; } /* * 下载微信服务器的图片 * media_id 微信的媒体id * type 保存图片类型 * */ public function getwximg2($mediaid,$file) { if(!class_exists('\jssdk') && !class_exists('\wxpayconfig')) { vendor('wxsdkapi.jssdk'); vendor('wxpayapi.lib.wxpay#config'); } $res = new \jssdk(c('weixinpay_config.appid'),c('weixinpay_config.appsecret')); $accesstoken = $res->getaccesstoken(); $picurl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$accesstoken&media_id=$mediaid"; return httpcopy($picurl,$file); } }

 

调用方法:

/**
     * 生成图片
     * @param varchar  tid 任务id
     * @httpmethod post
     * @response 响应数据
     * {
     *   "resulttype": "1000",
     *   "message": "上传成功",
     *   "appenddata": "图片路径",
     * }
     */
    public function uploadnavimg()
    {
        $tid=util::getsafetext(i('post.tid'));
        $imgeven = a('gszc/img','event');
        //查出公司名称
        $res = m('gszc_tasks as t')
            ->join('app_gszc_userinfo as u on u.tid=t.id')
            ->where('t.id='.$tid)
            ->field('u.*,t.lastname')
            ->find();

        //主营业务范围
        $zyywfws = explode('、',$res['zyywfw']);
        $zyywfw = array_slice($zyywfws, 0,3);  //获取前三个主营业范围
        $zyywfw2 = array_slice($zyywfws, 3,6);  //获取后三个主营业务范围

        $imagename = date("his",time())."_".rand(1111,9999).'.jpg';
        $dir = date('ymd');
        $path = 'uploads/company/'.$dir;
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建
            mkdir($path,0777,true);
        }
        $img = $imgeven->save_usershareimg($_server['document_root']."/uploads/test.png",'','',$_server['document_root']."/".$path."/". $imagename,$res['lastname'],$zyywfw, $zyywfw2, '',$_server['document_root']."/uploads/pingfang bold.ttf");

        if($img){
            //生成照片成功 保存到任务表里
            $tasks = m('gszc_tasks')->where('id='.$tid)->setfield('lastpic',$path."/".$imagename);
            if($tasks){
                $lujing = $path."/".$imagename;
                $this->array_return['errno']=self::__ok__;
                $this->array_return['errmsg']='生成成功!';
                $this->array_return['data']= $lujing ;
                $this->ajaxreturn($this->array_return);
            }
        }else{
            $this->array_return['errno']=self::__error__;
            $this->array_return['errmsg']='生成失败!';
            $this->array_return['data']=[];
            $this->ajaxreturn($this->array_return);
        }
    }
        $i = 528;
        $j = 113;
        foreach($zyywfw as $k=>$v){

            //设置前三个主营业务范围
            $this->copywritetext($savefile, $savefile, $v,254,253,254, $j , $i ,11,$font_path, array());
            $j = $j+135;

        }