學習要點:1.創建圖像2.簡單小案例
在php5 中,動態圖象的處理要比以前容易得多。PHP5 在php.ini 文件中包含了GD 擴展包,只需去掉GD 擴展包的相應注釋就可以正常使用了。PHP5 包含的GD 庫正是升級的GD2 庫,其中包含支持真彩圖像處理的一些有用的JPG 功能。 一般生成的圖形,通過PHP 的文檔格式存放,但可以通過HTML 的圖片插入方式SRC來直接獲取動態圖形。比如,驗證碼、水印、微縮圖等。
一.創建圖像
創建圖像的一般流程:1).設定標頭,告訴瀏覽器你要生成的MIME 類型。2).創建一個圖像區域,以后的操作都將基于此圖像區域。3).在空白圖像區域繪制填充背景。4).在背景上繪制圖形輪廓輸入文本。5).輸出最終圖形。6).清除所有資源。7).其他頁面調用圖像。
設定標頭指定MIME 輸出類型
<?phpheader('Content-Type: image/png');?>創建一個空白的圖像區域
<?php$im = imagecreatetruecolor(200,200);?>
在空白圖像區域繪制填充背景
<?php$blue = imagecolorallocate($im,0,102,255);imagefill($im,0,0,$blue);?>
在背景上繪制圖形輪廓輸入文本
<?php$white = imagecolorallocate($im,255,255,255);imageline($im,0,0,200,200,$white);imageline($im,200,0,0,200,$white);imagestring($im, 5, 80, 20, "Mr.Lee", $white);?>
輸出最終圖形
<?phpimagepng($im);?>
清除所有資源
<?phpimagedestroy($im);?>
其他頁面調用創建的圖形
<img src="Demo4.php" alt="PHP 創建的圖片" />
二.簡單小案例
簡單驗證碼
<?phpheader('Content-type: image/png');for($Tmpa=0;$Tmpa<4;$Tmpa++){ $nmsg.=dechex(rand(0,15));}$im = imagecreatetruecolor(75,25);$blue = imagecolorallocate($im,0,102,255);$white = imagecolorallocate($im,255,255,255);imagefill($im,0,0,$blue);imagestring($im,5,20,4,$nmsg,$white);imagepng($im);imagedestroy($im);?>加載已有的圖像
<?phpheader('Content-Type:image/png');define('__DIR__',dirname(__FILE__).'//');$im = imagecreatefrompng(__DIR__.'222.png');$white = imagecolorallocate($im,255,255,255);imagestring($im,3,5,5,'http://www.yc60.com',$white);imagepng($im);imagedestroy($im);?>加載已有的系統字體
<?php$text = iconv("gbk","utf-8","李炎恢");$font = 'C:/WINDOWS/Fonts/SIMHEI.TTF';imagettftext($im,20,0,30,30,$white,$font,$text);?>圖像微縮
<?phpheader('Content-type: image/png');define('__DIR__',dirname(__FILE__).'//');list($width, $height) = getimagesize(__DIR__.'222.png');$new_width = $width * 0.7;$new_height = $height * 0.7;$im2 = imagecreatetruecolor($new_width, $new_height);$im = imagecreatefrompng(__DIR__.'222.png');imagecopyresampled($im2, $im, 0, 0, 0, 0,$new_width, $new_height, $width, $height);imagepng($im2);imagedestroy($im);Imagedestroy($im2);?>注:文章出自李炎恢PHP視頻教程,本文僅限交流使用,不得用于商業用途,否則后果自負。
新聞熱點
疑難解答