1.基本步驟php
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午9:34 * 熟悉步驟 */ // 1.建立畫布 $width = 500; $height= 300; $image=imagecreatetruecolor($width,$height); // 2.建立顏色 $red=imagecolorallocate($image,255,0,0); $blue=imagecolorallocate($image,0,0,255); // 3.進行繪畫 // 水平繪製字符 imagechar($image,5,50,100,'K',$red); // 垂直繪製字符 imagecharup($image,4,100,100,'J',$blue); // 水平繪製字符串 imagestring($image,4,200,100,"Hello",$blue); // 4.輸出或保存 header('content-type:image/jpeg'); imagejpeg($image); //if(imagejpeg($image,'./1.jpg')) { // echo '保存成功'; //} else { // echo '保存失敗'; //} // 5.銷燬畫布 imagedestroy($image);
2.優化字體和畫布json
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午9:51 * 解決畫布黑底,字體太醜問題 */ // 建立畫布 $image=imagecreatetruecolor(500,500); // 建立顏色 $white=imagecolorallocate($image,255,255,255); $randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)); // 繪製填充矩形 imagefilledrectangle($image,0,0,500,500,$white); // 採用自定義字體繪畫 imagettftext($image,18,0,100,100,$randColor,'../ttf/Rekha.ttf',"Hello world!"); imagettftext($image,22,30,100,200,$randColor,'../ttf/msyh.ttf',"Hello world!"); // 展現 header('content-type:image/jpeg'); imagejpeg($image); // 銷燬 imagedestroy($image);
3.建立簡單的驗證碼canvas
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午10:38 * 實現驗證碼功能 */ // 建立畫布 $width=140; $height=50; $image=imagecreatetruecolor($width,$height); // 建立顏色 $white=imagecolorallocate($image,255,255,255); $randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)); // 繪製填充矩形 imagefilledrectangle($image,0,0,$width,$height,$white); // 開始繪製 $size=mt_rand(20,28); $angle=mt_rand(-10,10); $x=30; $y=35; $fontfile="../ttf/msyh.ttf"; $string=mt_rand(1000,9999); imagettftext($image,$size,$angle,$x,$y,$randColor,$fontfile,$string); // 展現 header('content-type:image/jpeg'); imagejpeg($image); // 銷燬 imagedestroy($image);
4.建立複雜的驗證碼api
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午10:49 */ // 隨機顏色 function getRandColor($image) { return imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)); } // 建立畫布 $width=140; $height=50; $image=imagecreatetruecolor($width,$height); // 建立顏色 $white=imagecolorallocate($image,255,255,255); // 繪製填充矩形 imagefilledrectangle($image,0,0,$width,$height,$white); // 開始繪製 $string = join('',array_merge(range(0,9),range('a','z'),range('A','Z'))); $length=4; for($i=0;$i<$length;$i++) { $size=mt_rand(20,28); $textWidth = imagefontwidth($size); $textHeight= imagefontheight($size); $angle=mt_rand(-10,10); // $x=20+30*$i; // $y=35; $x=($width/$length)*$i+$textWidth; $y=mt_rand($height/2,$height-$textHeight); $fontfile="../ttf/msyh.ttf"; $text = str_shuffle($string)[0];// 打亂以後取其一 imagettftext($image,$size,$angle,$x,$y,getRandColor($image),$fontfile,$text); } // 添加干擾元素 for($i=1;$i<=50;$i++) { imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),getRandColor($image)); } // 繪製線段 for ($i=1;$i<=3;$i++) { imageline($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$height),mt_rand(0,$width),getRandColor($image)); } // 展現 header('content-type:image/jpeg'); imagejpeg($image); // 銷燬 imagedestroy($image);
5.封裝驗證碼成函數dom
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午11:23 * 封裝驗證碼成函數 */ function getVerify($type,$length) { // 隨機顏色 function getRandColor($image) { return imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)); } // 建立畫布 $width=20+$length*40; $height=50; $image=imagecreatetruecolor($width,$height); // 建立顏色 $white=imagecolorallocate($image,255,255,255); // 繪製填充矩形 imagefilledrectangle($image,0,0,$width,$height,$white); /** * 默認是4 * 1-數字 * 2-字母 * 3-數字+字母 * 4-漢字 */ $type=$type?$type:1; $length=$length?$length:4; switch ($type) { case 1: // 數字 $string = join('',array_rand(range(0,9),$length)); break; case 2: // 字母 $string = join('',array_rand(array_flip(array_merge(range('a','z'),range('A','Z'))),$length)); break; case 3: // 數字+字母 $string = join('',array_rand(array_flip(array_merge(range(0,9),range('a','z'),range('A','Z'))),$length)); break; case 4: // 漢字 $str="湯,科,技,積,極,拓,展,人,工,智,能,領,域,尤,其,在,深,度,學,習,和,視,覺,計,算,方,面,其,科,研,能,力,讓,人,印,象,深,刻,阿,裏,巴,巴,在,人,工,智,能,領,域,的,投,入,已,爲,旗,下,業,務,帶,來,顯,著,效,益,今,後,我,們,將,繼,續,在,人,工,智,能,領,域,做,出,投,資,我,們,期,待,與,商,湯,科,技,的,戰,略,合,做,能,夠,激,發,更,多,創,新,爲,社,會,創,造,價,值"; $arr=explode(",",$str); $string = join('',array_rand(array_flip($arr),$length)); break; default: exit('非法參數'); break; } for($i=0;$i<$length;$i++) { $size=mt_rand(20,28); $textWidth = imagefontwidth($size); $textHeight= imagefontheight($size); $angle=mt_rand(-10,10); $x=($width/$length)*$i+$textWidth; $y=mt_rand($height/2,$height-$textHeight); $fontfile="../../ttf/msyh.ttf"; $text = mb_substr($string,$i,1,'UTF-8'); imagettftext($image,$size,$angle,$x,$y,getRandColor($image),$fontfile,$text); } // 添加干擾元素 for($i=1;$i<=50;$i++) { imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),getRandColor($image)); } // 繪製線段 for ($i=1;$i<=3;$i++) { imageline($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$height),mt_rand(0,$width),getRandColor($image)); } // 展現 header('content-type:image/jpeg'); imagejpeg($image); // 銷燬 imagedestroy($image); } getVerify(3,6);
6.縮略圖iphone
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午11:22 * 圖片處理 */ $filename = "../images/iphone7.jpg"; $fileInfo = getimagesize($filename); list($src_width,$src_height) = $fileInfo; // 縮放 $dst_w = 100; $dst_h = 100; // 建立目標畫布資源 $dst_image=imagecreatetruecolor($dst_w,$dst_h); // 經過圖片文件建立畫布資源 $src_image=imagecreatefromjpeg($filename); imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_width,$src_height); imagejpeg($dst_image,'thumbs/thumb_100x100.jpg'); // 展現 header('content-type:image/jpeg'); imagejpeg($dst_image); imagedestroy($dst_image);
7.等比例縮放函數
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午11:22 * 圖片處理 */ $filename = "../images/longmen.jpg"; if($fileInfo = getimagesize($filename)) { list($src_w,$src_h) = $fileInfo; } else { exit('文件不是真實圖片'); } // 等比例縮放 // 設置最大寬和高 $dst_w = 300; $dst_h = 600; $ratio_orig = $src_w / $src_h; if ($dst_w / $dst_h > $ratio_orig) { $dst_w = $dst_h * $ratio_orig; } else { $dst_h = $dst_w / $ratio_orig; } // 建立目標畫布資源 $dst_image=imagecreatetruecolor($dst_w,$dst_h); // 經過圖片文件建立畫布資源 $src_image=imagecreatefromjpeg($filename); imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h); imagejpeg($dst_image,'../thumbs/thumb_same.jpg'); // 展現 header('content-type:image/jpeg'); imagejpeg($dst_image); imagedestroy($dst_image); imagedestroy($src_image);
優化處理字體
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-9 * Time: 上午11:22 * 圖片處理 */ $filename = "../images/longmen.jpg"; if($fileInfo = getimagesize($filename)) { list($src_w,$src_h) = $fileInfo; $mime = $fileInfo['mime']; } else { exit('文件不是真實圖片'); } // image/jpeg image/gif image/png $createFun = str_replace('/','createfrom',$mime); $outFun = str_replace('/','',$mime); // 等比例縮放 // 設置最大寬和高 $dst_w = 300; $dst_h = 600; $ratio_orig = $src_w / $src_h; if ($dst_w / $dst_h > $ratio_orig) { $dst_w = $dst_h * $ratio_orig; } else { $dst_h = $dst_w / $ratio_orig; } // 建立目標畫布資源 $dst_image=imagecreatetruecolor($dst_w,$dst_h); // 經過圖片文件建立畫布資源 // $src_image=imagecreatefromjpeg($filename); $src_image=$createFun($filename); imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h); // imagejpeg($dst_image,'../thumbs/thumb_same.jpg'); $outFun($dst_image,'../thumbs/thumb_same.jpg'); // 展現 header('content-type:image/jpeg'); //imagejpeg($dst_image); $outFun($dst_image); imagedestroy($dst_image); imagedestroy($src_image);
8.文字水印優化
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-10 * Time: 上午10:56 * 加水印 */ $filename = "../images/longmen.jpg"; $fileInfo = getimagesize($filename); $mime = $fileInfo['mime']; $createFun = str_replace('/','createfrom',$mime); $outFun = str_replace('/',null,$mime); $image = $createFun($filename); //$red = imagecolorallocate($image,255,0,0); $red = imagecolorallocatealpha($image,255,0,0,50); // 實現透明 $fontfile = "../ttf/msyh.ttf"; imagettftext($image,30,0,30,50,$red,$fontfile,"China你好"); header('content-type:'.$mime); $outFun($image); imagedestroy($image);
GD庫綜合使用this
<?php /** * Created by PhpStorm. * User: jiqing * Date: 18-4-8 * Time: 上午11:58 */ class SiemensAction extends CommonAction{ public function _initialize() { parent::_initialize(); header( "Access-Control-Allow-Origin:*" ); } public function index(){ $url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; if ($url == 'hotel.caomall.net/index.php/Siemens'){ header('Location:http://hotel.caomall.net/index.php/Siemens/'); return false; } $this->assign('$random_num',rand(1111,9999)); $this->display(); } public function get_compose_pic() { vendor('Func.Json'); $json = new Json(); file_put_contents("./log/jiqing_log.txt", "\n".json_encode($_POST), FILE_APPEND); $logData = []; $logData = $_POST; // 建立畫布 $bg_w = $_POST['bgWidth']; $bg_h = $_POST['bgHeight']; $dpi = $_POST['dpi']; if ($dpi == 1) { $bg_w *= 3; $bg_h *= 3; } if ($dpi == 1.5) { $bg_w *= 2; $bg_h *= 2; } if ($dpi == 2) { $bg_w *= 1.5; $bg_h *= 1.5; } $img_w = $_POST['imgWidth']; $img_h = $_POST['imgHeight']; $percentRate = ($bg_w/1125); $img_h = $img_h * (bcdiv($bg_w,$img_w,2)); $img_w = $bg_w; if ($img_h > $bg_h) { $true_h = $bg_h; $true_h = $true_h - 30; // 防止過高 $true_w = $img_w; } else { $true_h = $img_h; $true_w = $img_w; } $logData['true_h'] = $true_h; $logData['true_w'] = $true_w; $canvas_w = $true_w + 72; $canvas_h = $true_h + 212; $canvasImage = imagecreatetruecolor($canvas_w,$canvas_h); // 建立顏色 $white=imagecolorallocate($canvasImage,255,255,255); $green = imagecolorallocatealpha($canvasImage,103,159,27,20); // 實現透明 // 繪製填充矩形 imagefilledrectangle($canvasImage,0,0,$canvas_w,$canvas_h,$white); // 添加固定文字 $fontsize1 = 44*$percentRate; $text1 = "世界地球日 環保有創意"; $fontsize2 = 24*$percentRate; $text2 = "長 按 二 維 碼 定 制 你 的 環 保 創 意 海 報"; imagettftext($canvasImage,$fontsize1,0,36,$true_h + 36 + 80 ,$green,'/siemens/font/msyh.ttf',$text1); imagettftext($canvasImage,$fontsize2,0,36,$true_h + 36 + 130 ,$green,'/siemens/font/msyh.ttf',$text2); \PHPQRCode\QRcode::png("http://".$_SERVER['HTTP_HOST']."/index.php/Siemens/index", "./tmp/qrcode.png", 'L', 4, 2); // 添加二維碼 $qr_url = "http://".$_SERVER['SERVER_NAME']."/tmp/qrcode.png"; $qrImageZoomInfo = $this->_imageZoom($qr_url,true,150,150); imagecopymerge($canvasImage,$qrImageZoomInfo['image'],$canvas_w - 186,$canvas_h - 170,0,0,$qrImageZoomInfo['width'],$qrImageZoomInfo['height'],80); // 獲取基礎圖片 $bgId = $_POST['bgId']; $baseImageInfo = $this->_getBasePic($bgId); // 固定縮放處理 $baseImage = $this->_imageZoomFixed($baseImageInfo['imgUrl'],true,$img_w,$img_h); $baseImage = $baseImage['image']; // 圖片裁剪處理 $baseImage = $this->_imageCut($baseImage,$true_w,$true_h); // 添加logo $plugins = json_decode($_POST['plugins'],true)[0]; if ($plugins) { // 有貼圖 if ($plugins['type'] == 1) { // 貼圖 $chartlet_w = $plugins['width']; $chartlet_h = $plugins['height']; $chartlet_top = $plugins['top']; $chartlet_left= $plugins['left']; if ($dpi == 1.5) { $chartlet_w *= 2; $chartlet_h *= 2; $chartlet_top *= 2; $chartlet_left *= 2; } if ($dpi == 2) { $chartlet_w *= 1.5; $chartlet_h *= 1.5; $chartlet_top *= 1.5; $chartlet_left *= 1.5; } if ($dpi == 1) { $chartlet_w *= 3; $chartlet_h *= 3; $chartlet_top *= 3; $chartlet_left *= 3; } $chartlet_url = "http://".$_SERVER['SERVER_NAME'].$plugins['src']; $chartletImageZoomInfo = $this->_imageZoomFixed($chartlet_url,true,$chartlet_w,$chartlet_h); imagecopymerge($baseImage,$chartletImageZoomInfo['image'],$chartlet_left,$chartlet_top,0,0,$chartlet_w,$chartlet_h,100); } else { // 文字 $text_w = $plugins['width']; $text_h = $plugins['height']; $text_top = $plugins['top']; $text_left= $plugins['left']; if ($dpi == 1.5) { $text_w *= 2; $text_h *= 2; $text_top *= 2; $text_left *= 2; } if ($dpi == 2) { $text_w *= 1.5; $text_h *= 1.5; $text_top *= 1.5; $text_left *= 1.5; } if ($dpi == 1) { $text_w *= 3; $text_h *= 3; $text_top *= 3; $text_left *= 3; } $customText = $plugins['val']; $customText = $this->_str_line($customText); imagettftext($baseImage,44,0,$text_left,$text_top,$white,'/siemens/font/msyh.ttf',$customText); } } // 增長logo $logo_url = "http://".$_SERVER['SERVER_NAME']."/siemens/img/logo.png"; $logoImageInfo = $this->_imageZoom($logo_url,true,300); imagecopymerge($baseImage,$logoImageInfo['image'],30,30,0,0,$logoImageInfo['width'],$logoImageInfo['height'],80); // 合成到主畫布 imagecopymerge($canvasImage,$baseImage,36,36,0,0,$true_w,$true_h,100); $outImgPath = '/tmp/'.date('YmdHis').rand(1000,9999).'.jpg'; $flag = imagejpeg($canvasImage,".".$outImgPath); // 日誌 $logData['outImgPath'] = $outImgPath; file_put_contents("./log/jiqing_log.txt", "\n".json_encode($logData), FILE_APPEND); if($flag){ $json->setAttr('imgurl',$outImgPath); $json->setErr(0,'圖片合成成功'); $json->Send(); }else{ $json->setErr(10001,'圖片合成失敗'); $json->Send(); } } private function _str_line($str,$len = 10) { function mb_str_split($str){ return preg_split('/(?<!^)(?!$)/u', $str ); } $str_arr = mb_str_split($str); $i = 0; $new_str = ""; foreach($str_arr as $val) { $new_str .= $val; $i ++ ; if ($i % 10 == 0) { $new_str .= "\r\n"; } } return $new_str; } // 圖片裁剪 private function _imageCut($source,$width,$height,$source_x = 0,$source_y = 0) { // 建立畫布 $copyimage=imagecreatetruecolor($width,$height); // 建立顏色 $white=imagecolorallocate($copyimage,255,255,255); imagefilledrectangle($copyimage,0,0,$width,$height,$white); imagecopyresampled($copyimage,$source,0,0,$source_x,$source_y,$width,$height,$width,$height); return $copyimage; } // 圖片等比例縮放,背景透明處理 private function _imageZoom($filename,$is_transparent = true,$dst_w="200",$dst_h="200") { if($fileInfo = getimagesize($filename)) { list($src_w,$src_h) = $fileInfo; $mime = $fileInfo['mime']; } else { exit('文件不是真實圖片'); } // image/jpeg image/gif image/png $createFun = str_replace('/','createfrom',$mime); $outFun = str_replace('/','',$mime); // 等比例縮放 $ratio_orig = $src_w / $src_h; if ($dst_w / $dst_h > $ratio_orig) { $dst_w = $dst_h * $ratio_orig; } else { $dst_h = $dst_w / $ratio_orig; } // 建立目標畫布資源 $dst_image=imagecreatetruecolor($dst_w,$dst_h); // 透明處理 if ($is_transparent) { $color=imagecolorallocate($dst_image,204,204,204); imagecolortransparent($dst_image,$color); imagefill($dst_image,0,0,$color); } // 經過圖片文件建立畫布資源 $src_image=$createFun($filename); imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h); $fileInfo['width'] = $dst_w; $fileInfo['height'] = $dst_h; $fileInfo['image'] = $dst_image; imagedestroy($src_image); // imagedestroy($dst_image); return $fileInfo; } private function _imageZoomFixed($filename,$is_transparent = true,$dst_w="200",$dst_h="200") { if($fileInfo = getimagesize($filename)) { list($src_w,$src_h) = $fileInfo; $mime = $fileInfo['mime']; } else { exit('文件不是真實圖片'); } // image/jpeg image/gif image/png $createFun = str_replace('/','createfrom',$mime); $outFun = str_replace('/','',$mime); // 建立目標畫布資源 $dst_image=imagecreatetruecolor($dst_w,$dst_h); // 透明處理 if ($is_transparent) { $color=imagecolorallocate($dst_image,153,153,153); imagecolortransparent($dst_image,$color); imagefill($dst_image,0,0,$color); } // 經過圖片文件建立畫布資源 $src_image=$createFun($filename); imagecopyresampled($dst_image,$src_image,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h); $fileInfo['width'] = $dst_w; $fileInfo['height'] = $dst_h; $fileInfo['image'] = $dst_image; imagedestroy($src_image); // imagedestroy($dst_image); return $fileInfo; } // 獲取基礎圖片信息 private function _getBasePic($media_id) { // 獲取accessToken $access_token_url = C('WECHAT_PROXY_HOST') . 'AccessToken/get'; $access_res = Http::doGet($access_token_url); $json = json_decode($access_res, true); $accessToken = $json['data']['access_token']; $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$accessToken."&media_id=".$media_id; return $this->_getImageInfo($url); } // 獲取圖片信息 private function _getImageInfo($filename) { if (@!$info = getimagesize($filename)) { exit('文件不是真實圖片'); } $fileInfo['width'] = $info[0]; $fileInfo['height']= $info[1]; $mime = image_type_to_mime_type($info[2]); $createFun = str_replace('/','createfrom',$mime); $outFun = str_replace('/','',$mime); $fileInfo['createFun'] = $createFun; $fileInfo['outFun'] = $outFun; $fileInfo['ext'] = strtolower(image_type_to_extension($info[2])); $fileInfo['imgUrl'] = $filename; return $fileInfo; } }