d=====( ̄▽ ̄*)b
引語
php不僅僅局限於html的輸出,還可以創建和操作各種各樣的圖像文件,如GIF、PNG、JPEG、WBMP、XBM等。
php還可以將圖像流直接顯示在瀏覽器中。
要處理圖像,就要用到php的GD庫。
ps:確保php.ini文件中可以加載GD庫。可以在php.ini文件中找到“;extension=php_gd2.dll”,將選項前的分號刪除,保存,再重啟Apache服務器即可。
步驟
在php中創建一個圖像一般需要四個步驟:
1.創建一個背景圖像,以后的所有操作都是基於此背景。
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); //清空內存
效果: