將頭像、文字和二維碼三部分,合成一張宣傳圖片


這里是thinkphp框架用到的圖片合成,邏輯都是一樣的,不用框架純php的話,只是文件的保存位置沒有那么多的規定,邏輯什么的還是一樣的。

作者:悅~  地址:https://www.cnblogs.com/nuanai/

一、二維碼生成在https://www.cnblogs.com/nuanai/p/10501946.html博客中寫到過的,在這就不詳細的說了    作者:悅~  地址:https://www.cnblogs.com/nuanai/

二、首先將合成圖片所用到的內容先形成數組,包括各元素所在的位置、顏色、大小等,然后將數組傳到合成圖片用到的方法中

注意:createPoster(內容,圖片名稱)方法的傳值,如果不傳圖片名稱的話,直接在網頁中顯示,如果有圖片名稱得話保存在本地,可以減少每次圖片的生成時間,前端直接調用保存在本地的圖片就可以了   作者:悅~  地址:https://www.cnblogs.com/nuanai/

	public function Xian(){
		$tid = 2;  //掃描二維碼傳入的id值
		//二維碼生成
		$url = "http://www.baidu.com";
		$level=3;
		$size=4;
		Vendor('phpqrcode.phpqrcode');
		$errorCorrectionLevel = intval($level) ;//容錯級別
		$matrixPointSize = intval($size);//生成圖片大小
		$object = new \QRcode(); //調用二維碼插件
		$path = "Public/ER/" . $tid . ".png"; //本地文件存儲路徑
		$object->png($url, $path, $errorCorrectionLevel, $matrixPointSize, 2);
		//二維碼生成
		
		//圖片所需要的內容
		$headimgurl = "https://image.so.com/view?q=%E6%A8%B1%E8%8A%B1%E5%9B%BE%E7%89%87&listsrc=sobox&listsign=15d7d9ebd0cd621a7e74c66a2b57aff2&src=360pic_strong&correct=%E6%A8%B1%E8%8A%B1%E5%9B%BE%E7%89%87&ancestor=list&cmsid=a7ec45ccb1b3e723a083d57001e3165b&cmran=0&cmras=6&cn=0&gn=0&kn=28&offspring=85bc14812e545b0c30263ea459328a2b&multiple=0&gsrc=1&currsn=0&jdx=17";
		//頭像可以通過數據庫查找替換
		$nickname = "你好";  //昵稱可以通過數據庫查找替換
		$erid = 2; //這個是保存的圖片的名字,可以通過數據庫進行替換
		
		$header = array(
'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding: gzip, deflate',);
		$url=$headimgurl;
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		$data = curl_exec($curl);
		$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);curl_close($curl);
		if ($code == 200) {
			//把URL格式的圖片轉成base64_encode格式的!
			$imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
		}
		
		$img_content=$imgBase64Code;  //圖片內容
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result))
		{
			$type = $result[2];  //得到圖片類型png?jpg?gif?
			$new_file = 'Public/ER/'.$erid.'.'.$type;  //圖片的路徑找到圖片
			if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content))))
			{  
				$config = array(
					    'text'=>array(
					        array(
					            'text'=>$nickname,  //微信用戶昵稱
					            'left'=>750,
					            'top'=>310,
					            'fontPath'=>'Public/bootstrap/fonts/simhei.ttf', //字體文件
					            'fontSize'=>44, //字號
					            'fontColor'=>'0,147,82', //字體顏色
					            'angle'=>0,
					        )
					    ),
					    'image'=>array(
					        array(
								'url'=>'Public/ER/'.$erid.'.png',//用戶的生成的二維碼
					            'left'=>422,
					            'top'=>-200,
					            'stream'=>0,//圖片資源是否是字符串圖像流
					            'right'=>0,
					            'bottom'=>0,
					            'width'=>500,
					            'height'=>500,
					            'opacity'=>100
					        ),
					        array(
					            'url'=>$new_file,  //用戶頭像
					            'left'=>280,
					            'top'=>255,
					            'right'=>0,
								'stream'=>0,
					            'bottom'=>0,
					            'width'=>200,
					            'height'=>200,
					            'opacity'=>100
					        ),
					    ),
					    'background'=>'Public/img/hai.jpg',  //合成用的背景圖
					    
					);
					$filename = 'Public/ER/'.$erid.'.jpg';
					$filurl = $erid.'.jpg';
					$this->createPoster($config,$filename);  //調用方法傳值,1.合成圖片用到的昵稱、背景圖、二維碼 
					$this->assign("filurl",$filurl);  //注入前端顯示
					$this->show();

			 }
		}

	}

  

三、其次下面是圖片合成用到的方法   作者:悅~  地址:https://www.cnblogs.com/nuanai/

/**
	 * 生成宣傳海報
	 * @param  array 	參數,包括圖片和文字
	 * @param  string 	$filename 生成海報文件名,不傳此參數則不生成文件,直接輸出圖片
	 * @return [type] [description]
	 */
	function createPoster($config=array(),$filename=""){
	    //如果要看報什么錯,可以先注釋調這個header 
		if(empty($filename)) header("content-type: image/png");
	 
	    $imageDefault = array(
	        'left'=>0,
	        'top'=>0,
	        'right'=>0,
	        'bottom'=>0,
	        'width'=>100,
	        'height'=>100,
	        'opacity'=>100
	    );
	    $textDefault =  array(
	        'text'=>'',
	        'left'=>0,
	        'top'=>0,
	        'fontSize'=>40,             //字號
	        'fontColor'=>'255,255,255', //字體顏色
	        'angle'=>0,
	    );
	 
	    $background = $config['background'];//海報最底層得背景  
	    //背景方法
	    $backgroundInfo = getimagesize($background);
	    $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
	    $background = $backgroundFun($background);
	 
	    $backgroundWidth = imagesx($background);    //背景寬度
	    $backgroundHeight = imagesy($background);   //背景高度
	 
	    $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight); 
	    $color = imagecolorallocate($imageRes, 0, 0, 0);  
	    imagefill($imageRes, 0, 0, $color);  
	 
	    //imageColorTransparent($imageRes, $color);    //顏色透明
	 
	    imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));  
	 
	    //處理了圖片
	    if(!empty($config['image'])){
	        foreach ($config['image'] as $key => $val) {
	            $val = array_merge($imageDefault,$val);
	 
	            $info = getimagesize($val['url']);
	            $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
				if($val['stream']){		//如果傳的是字符串圖像流
					$info = getimagesizefromstring($val['url']);
					$function = 'imagecreatefromstring';
				}
	            $res = $function($val['url']);
	            $resWidth = $info[0];
	            $resHeight = $info[1];
	            //建立畫板 ,縮放圖片至指定尺寸
	            $canvas=imagecreatetruecolor($val['width'], $val['height']); 
	            imagefill($canvas, 0, 0, $color);
	            //關鍵函數,參數(目標資源,源,目標資源的開始坐標x,y, 源資源的開始坐標x,y,目標資源的寬高w,h,源資源的寬高w,h) 
	            imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight); 
	            $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
	            $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
	            //放置圖像
	            imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左,上,右,下,寬度,高度,透明度 
	        }
	    }
	 
	    //處理文字
	    if(!empty($config['text'])){
	        foreach ($config['text'] as $key => $val) {
	            $val = array_merge($textDefault,$val);
	            list($R,$G,$B) = explode(',', $val['fontColor']);
	            $fontColor = imagecolorallocate($imageRes, $R, $G, $B); 
	            $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
	            $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
	            imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']); 
	        }
	    }
	
	    //生成圖片  
	    if(!empty($filename)){
	        $res = imagejpeg ($imageRes,$filename,90); //保存到本地
			imagedestroy($imageRes);
			if(!$res) return false;
			return $filename;
	    }else{
	        imagejpeg ($imageRes);			//在瀏覽器上顯示
			imagedestroy($imageRes);
	    }  
	}

  

四、最后是在前端顯示就可以了   作者:悅~  地址:https://www.cnblogs.com/nuanai/

用圖片標簽或者背景圖屬性這要看自己的習慣了 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM