PHP之GD函数的使用
本文講解常用GD函數(shù)的應(yīng)用
1.一個(gè)簡單的圖像
我們先看一個(gè)例子:
<?php$w = 200; $h = 200; $img = imagecreatetruecolor($w,$h); $white = imagecolorallocate($img,255,255,255); $blue = imagecolorallocate($img,0,0,64); imagefill($img,0,0,$blue); imageline($img,0,0,$w,$h,$white); imagestring($img,4,50,150,'Sales',$white); Header('Content-type: image/png'); imagepng($img); imagedestroy($img);?>運(yùn)行結(jié)果:
這段代碼中我們用了一下幾個(gè)函數(shù):
imagecreatetruecolor - 新建一個(gè)真彩色圖像.函數(shù)原型為resource imagecreatetruecolor ( int $width , int $height )。imagecreatetruecolor() 返回一個(gè)圖像標(biāo)識(shí)符,代表了一幅大小為 x_size 和 y_size 的黑色圖像。
imagecolorallocate - 為一幅圖像分配顏色. 函數(shù)原型為int imagecolorallocate ( resource $image , int $red , int $green , int $blue ). imagecolorallocate() 返回一個(gè)標(biāo)識(shí)符,代表了由給定的 RGB 成分組成的顏色。red,green 和 blue 分別是所需要的顏色的紅,綠,藍(lán)成分。這些參數(shù)是 0 到 255 的整數(shù)或者十六進(jìn)制的 0x00 到 0xFF。imagecolorallocate() 必須被調(diào)用以創(chuàng)建每一種用在 image 所代表的圖像中的顏色。
imagefill - 區(qū)域填充. 函數(shù)原型為bool imagefill ( resource $image , int $x , int $y , int $color ). imagefill() 在 image 圖像的坐標(biāo) x,y(圖像左上角為 0, 0)處用 color 顏色執(zhí)行區(qū)域填充(即與 x, y 點(diǎn)顏色相同且相鄰的點(diǎn)都會(huì)被填充)。
imagestring - 水平地畫一行字符串. 函數(shù)原型為bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col ). imagestring() 用 col 顏色將字符串 s 畫到 image 所代表的圖像的 x,y 坐標(biāo)處(這是字符串左上角坐標(biāo),整幅圖像的左上角為 0,0)。如果 font 是 1,2,3,4 或 5,則使用內(nèi)置字體。
以 PNG 格式將圖像輸出到瀏覽器或文件 - 以 PNG 格式將圖像輸出到瀏覽器或文件. 函數(shù)原型為bool imagepng ( resource $image [, string $filename ] ). imagepng() 將 GD 圖像流(image)以 PNG 格式輸出到標(biāo)準(zhǔn)輸出(通常為瀏覽器),或者如果用 filename 給出了文件名則將其輸出到該文件。
imagedestroy - 銷毀一圖像 函數(shù)原型為bool imagedestroy ( resource $image ). imagedestroy() 釋放與 image 關(guān)聯(lián)的內(nèi)存。image 是由圖像創(chuàng)建函數(shù)返回的圖像標(biāo)識(shí)符,例如 imagecreatetruecolor()。
2.使用文本和字體創(chuàng)建圖像
<?php$button_text = $_REQUEST['button_text']; $button_text_color = $_REQUEST['color']; if (empty($button_text) || empty($button_text_color)) {echo 'Please input text';exit; }//創(chuàng)建畫布 $img = imagecreatefrompng($button_text_color . '_button.png');//設(shè)置按鈕的寬和高 $width_image = imagesx($img); $height_image = imagesy($img); //沒有邊界的寬和高,邊界設(shè)置定為18個(gè)像素 $margin = 18; $width_image_without_margins = $width_image - 2 * $margin; $height_image_without_margins = $height_image - 2 * $margin;//字體 $font_size = 240; //使用字體必須告訴GD2字體的位置 putenv('GDFONTPATH=/System/Library/Fonts'); $fontname = 'MarkerFelt.ttc';//循環(huán)遍歷邊界,尋找合適的字體font do {$font_size--;$bbox = imagettfbbox($font_size, 0, $fontname, $button_text);$left = $bbox[0];$right = $bbox[2];$width_text = $right - $left;$height_text = abs($bbox[7] - $bbox[1]); }while ($font_size > 8 && ($width_text > $width_image_without_margins || $height_text > $height_image_without_margins)) ;//檢查文字邊界問題 if ($width_text > $width_image_without_margins || $height_text > $height_image_without_margins) {echo 'Text given will not fit button. <br />'; }else {//計(jì)算文本坐標(biāo)$text_x = $width_image / 2.0 - $width_text / 2.0;$text_y = $height_image / 2.0 - $height_text / 2.0;//矯正if ($left < 0) {$text_x = abs($left);}$above_line_text = abs($bbox[7]);$text_y += $above_line_text;$text_y -= 2;//渲染文本$white = imagecolorallocate($img, 255, 255, 255);imagettftext($img, $font_size, 0, $text_x, $text_y, $white, $fontname, $button_text);Header('Content-type: image/png');imagepng($img);}imagedestroy($img);?>演示頁面為:
除了上邊我們解釋的函數(shù)外,又新增了一些新的函數(shù),我們一一作出解釋:
imagecreatefrompng - 由文件或 URL 創(chuàng)建一個(gè)新圖象。函數(shù)原型為resource imagecreatefrompng ( string $filename )。imagecreatefrompng() 返回一圖像標(biāo)識(shí)符,代表了從給定的文件名取得的圖像。
imagesx - 取得圖像寬度。 函數(shù)原型為int imagesx ( resource $image )。imagesx() 返回 image 所代表的圖像的寬度。
imagesy - 取得圖像高度。 函數(shù)原型為int imagesy ( resource $image )。 imagesy() 返回 image 所代表的圖像的高度。
imagettfbbox - 取得使用 TrueType 字體的文本的范圍。函數(shù)原型為array imagettfbbox ( float $size , float $angle , string $fontfile , string $text )。本函數(shù)計(jì)算并返回一個(gè)包圍著 TrueType 文本范圍的虛擬方框的像素大小。其中參數(shù)size:像素單位的字體大小,angle:text 將被度量的角度大小,fontfile:TrueType 字體文件的文件名(可以是 URL)。根據(jù) PHP 所使用的 GD 庫版本,可能嘗試搜索那些不是以 '/' 開頭的文件名并加上 '.ttf' 的后綴并搜索庫定義的字體路徑,text:要度量的字符串。
imagettfbbox() 返回一個(gè)含有 8 個(gè)單元的數(shù)組表示了文本外框的四個(gè)角:
角標(biāo)坐標(biāo) 0 左下角 X 位置 1 左下角 Y 位置 2 右下角 X 位置 3 右下角 Y 位置 4 右上角 X 位置 5 右上角 Y 位置 6 左上角 X 位置 7 左上角 Y 位置 這些點(diǎn)是相對(duì)于文本的而和角度無關(guān),因此“左上角”指的是以水平方向看文字時(shí)其左上角。
本函數(shù)同時(shí)需要 GD 庫和 FreeType 庫。逆時(shí)針方向imagettftext - 用 TrueType 字體向圖像寫入文本。 函數(shù)原型為array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )。使用 TrueType 字體將 指定的 text 寫入圖像。其中text參數(shù)使用UTF-8 編碼的文本字符串。
3.繪制圖像與用圖表描述數(shù)據(jù)
<?php /********************************************************Database query to get poll info ********************************************************///get vote $vote = $_REQUEST['vote'];//login mysql @ $db = new mysqli('127.0.0.1', 'poll', 'poll', 'poll'); if (mysqli_connect_errno()) {echo 'Could not connect to db <br />';exit; }if (!empty($vote)) {$vote = addslashes($vote);//update$query = 'update poll_results set num_votes = num_votes + 1 where candidate = \'' . $vote . '\'';$result = $db -> query($query);if (!$result) {echo 'Could not connect to db <br />';exit;} //query$query = 'select * from poll_results';$result = $db -> query($query);if (!$result) {echo 'Could not connect to db <br />';exit;} $num_candidates = $result -> num_rows;$total_votes = 0;while ($row = $result -> fetch_object()) {$total_votes += $row -> num_votes;}$result -> data_seek(0);/********************************************************Initial calculations for graph ********************************************************/ //使用字體必須告訴GD2字體的位置 putenv('GDFONTPATH=/System/Library/Fonts'); $fontname = 'Times.dfont'; $width = 600; $left_margin = 50; $right_margin = 50; $bar_height = 40; $bar_spacing = $bar_height / 2; $title_size = 16; $main_size = 12; $small_size = 12; $text_indent = 10;$x = $left_margin + 60; $y = 50; $bar_unit = ($width - ($x + $right_margin)) / 100; $height = $num_candidates * ($bar_height + $bar_spacing) + 50;/********************************************************Setup base image ********************************************************/ $img = imagecreatetruecolor($width, $height);$white = imagecolorallocate($img, 255, 255, 255); $blue = imagecolorallocate($img, 0, 64, 128); $black = imagecolorallocate($img, 0, 0, 0); $pink = imagecolorallocate($img, 255, 78, 243);$text_color = $black; $percent_color = $black; $line_color = $black; $bg_color = $white; $bar_color = $blue; $number_color = $pink;imagefilledrectangle($img, 0, 0, $width, $height, $white); imagerectangle($img, 0, 0, $width - 1, $height - 1, $line_color);//Add title $title = 'Poll Result'; $title_dimensions = imagettfbbox($title_size, 0, $fontname, $title); $title_length = $title_dimensions[2] - $title_dimensions[0]; $title_height = abs($title_dimensions[7] - $title_dimensions[1]); $title_above_line = abs($title_dimensions[7]); $title_x = ($width - $title_length) / 2; $title_y = ($y - $title_height) / 2; imagettftext($img, $title_size, 0, $title_x, $title_y, $text_color, $fontname, $title); imageline($img, $x, $y - 5, $x, $height - 15, $line_color);/********************************************************Draw data into gragh ********************************************************/ while ($row = $result -> fetch_object()) {$percent = 0;if ($total_votes > 0) {$percent = intval($row -> num_votes / $total_votes * 100);}$percent_cahr = eurofix('%');$percent_dimension = imagettfbbox($main_size, 0, $fontname, $percent . $percent_cahr);$percent_lenght = $percent_dimension[2] - $percent_dimension[0];imagettftext($img, $main_size, 0, $width - $percent_lenght - $text_indent, $y + $bar_height / 2,$percent_color, $fontname, $percent . $percent_cahr);$bar_lenght = $x + $percent * $bar_unit; imagefilledrectangle($img, $x, $y - 2, $bar_lenght, $y + $bar_height, $bar_color); imagettftext($img, $main_size, 0, $text_indent, $y + $bar_height / 2,$text_color, $fontname, $row -> candidate); imagerectangle($img, $bar_lenght, $y - 2, $x + (100 * $bar_unit), $y + $bar_height, $line_color); imagettftext($img, $small_size, 0, $x + (100 * $bar_unit) - 50, $y + $bar_height / 2,$number_color, $fontname, $row -> num_votes . '/' . $total_votes);$y = $y + $bar_height + $bar_spacing;}header('Content-type: image/png'); imagepng($img); imagedestroy($img);}function eurofix($str) { $euro=utf8_encode('€'); $str = preg_replace('/\x80/',$euro,$str); return ($str); } ?>這上邊的代碼使用了我們上邊沒有介紹的函數(shù)有:
imagefilledrectangle - 畫一矩形并填充 函數(shù)原型為:bool imagefilledrectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )。imagefilledrectangle() 在 image 圖像中畫一個(gè)用 color 顏色填充了的矩形,其左上角坐標(biāo)為 x1,y1,右下角坐標(biāo)為 x2,y2。0, 0 是圖像的最左上角。
imagerectangle - 畫一個(gè)矩形 函數(shù)原型為:bool imagerectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $col )。imagerectangle() 用 col 顏色在 image 圖像中畫一個(gè)矩形,其左上角坐標(biāo)為 x1, y1,右下角坐標(biāo)為 x2, y2。圖像的左上角坐標(biāo)為 0, 0。
我們新建一個(gè)vote.html文件,并寫了如下的代碼:
<html><head><title>Pop Poll</title></head><body><form method="post" action="show_poll.php"><h1>Pop Poll</h1><p>Who will you vote for in the election?</p><input type="radio" name="vote" value="John Smith">John Smith <br /><input type="radio" name="vote" value="Mary Jones" >Mary Jones <br /><input type="radio" name="vote" value="Fred Bloggs" >Fred Bloggs <br /> <br /><input type="submit" value="Show results"> </form></body> </html>運(yùn)行后:
選擇后,點(diǎn)擊Show results 就成功繪制了表格
說明
本文只演示了GD的部分函數(shù),查看全部函數(shù)和用法,點(diǎn)擊這個(gè)網(wǎng)站http://php.net/manual/zh/ref.image.php
轉(zhuǎn)載于:https://www.cnblogs.com/machao/p/5991858.html
總結(jié)
以上是生活随笔為你收集整理的PHP之GD函数的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第十三章:Python の 网络编程进阶
- 下一篇: Orchard详解--第一篇 介绍