<?php /** * Created by PhpStorm. * User: Administrator */ namespace HomeEvent; use ThinkImage; use ThinkUpload; 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); } }
相關教學:PHP視訊教學
以上就是thinkphp框架 如何利用GD庫在圖片上編寫文字(程式碼範例)的詳細內容,更多請關注TW511.COM其它相關文章!