PHP圖形圖像處理之初識GD庫

d=====( ̄▽ ̄*)bphp

 

引語html

 

php不單單侷限於html的輸出,還能夠建立和操做各類各樣的圖像文件,如GIF、PNG、JPEG、WBMP、XBM等。瀏覽器

php還能夠將圖像流直接顯示在瀏覽器中。服務器

要處理圖像,就要用到php的GD庫。函數

ps:確保php.ini文件中能夠加載GD庫。能夠在php.ini文件中找到「;extension=php_gd2.dll」,將選項前的分號刪除,保存,再重啓Apache服務器便可。字體

 

步驟spa

 

在php中建立一個圖像通常須要四個步驟:code

1.建立一個背景圖像,之後的全部操做都是基於此背景。htm

2.在圖像上繪圖等操做。對象

3.輸出最終圖像。

4.銷燬內存中的圖像資源。

 

1.建立背景圖像

 

下面的函數能夠返回一個圖像標識符,表明了一個寬爲x_size像素、高爲y_size像素的背景,默認爲黑色。

 1 resource imagecreatetruecolor(int x_size , int y_size) 

在圖像上繪圖須要兩個步驟:首先須要選擇顏色。經過imagecolorallocate()函數建立顏色對象。

 1 int imagecolorallocate(resource image, int red, int green, int blue) 

而後將顏色繪製到圖像上。

 1 bool imagefill(resource image, int x, int y, int color) 

imagefill()函數會在image圖像的座標(x,y)處用color顏色進行填充。

 

2.在圖像上繪圖

 

 1 bool iamgeline(resource image, int begin_x, int begin_y, int end_x, int end_y, int color) 

imageline()函數用color顏色在圖像image中畫出一條從(begin_x,begin_y)到(end_x,end_y)的線段。

 1 bool imagestring(resource image, int font, int begin_x, int begin_y, string s, int color ) 

imagestring()函數用color顏色將字符串s畫到圖像image的(begin_x,begin_y)處(這是字符串的左上角座標)。若是font等於1,2,3,4或5,則使用內置字體,同時數字表明字體的粗細。

若是font字體不是內置的,則須要導入字體庫後使用。

 

3.輸出最終圖像

 

建立圖像之後就能夠輸出圖形或者保存到文件中了,若是須要輸出到瀏覽器中須要使用header()函數發送一個圖形的報頭「欺騙」瀏覽器,使它認爲運行的php頁面是一個圖像。

 1 header("Content-type: image/png"); 

發送數據報頭之後,利用imagepng()函數輸出圖形。後面的filename可選,表明生成的圖像文件的保存名稱。

 1 bool image(resource image [, string filename]) 

 

4.銷燬相關的內存資源

 

最後須要銷燬圖像佔用的內存資源。

 1 bool imagedestroy(resource image) 

 

例子:

 1 <?php
 2 $width=300;                                              //圖像寬度
 3 $height=200;                                             //圖像高度
 4 $img=imagecreatetruecolor($width,$height);               //建立圖像
 5 $white=imagecolorallocate($img,255,255,255);             //白色
 6 $black=imagecolorallocate($img,0,0,0);                   //黑色
 7 $red=imagecolorallocate($img,255,0,0);                   //紅色
 8 $green=imagecolorallocate($img,0,255,0);                 //綠色
 9 $blue=imagecolorallocate($img,0,0,255);                  //藍色
10 imagefill($img,0,0,$white);                              //將背景設置爲白色
11 imageline($img,20,20,260,150,$red);                      //畫出一條紅色的線
12 imagestring($img,5,50,50,"hello,world!!",$blue);       //顯示藍色的文字
13 header("content-type: image/png");                    //輸出圖像的MIME類型
14 imagepng($img);                                          //輸出一個PNG圖像數據
15 imagedestroy($img);                                      //清空內存

  效果:

相關文章
相關標籤/搜索