13.1.2 使用GD庫畫圖
GD庫圖像繪制的步驟
在PHP中創(chuàng)建一個圖像應(yīng)該完成如下所示的4個步驟:
1.創(chuàng)建一個背景圖像(也叫畫布),以后的操作都基于此背景圖像绵疲。
2.在背景上繪制圖像輪廓或輸入文本找御。
3.輸出最終圖形
4.釋放資源
<?php
//1. 創(chuàng)建畫布
$im = imageCreateTrueColor(200, 200); //建立空白背景
$white = imageColorAllocate ($im, 255, 255, 255); //設(shè)置繪圖顏色
$blue = imageColorAllocate ($im, 0, 0, 64);
//2. 開始繪畫
imageFill($im, 0, 0, $blue); //繪制背景
imageLine($im, 0, 0, 200, 200, $white); //畫線
imageString($im, 4, 50, 150, 'Sales', $white); //添加字串
//3. 輸出圖像
header('Content-type: image/png');
imagePng ($im); //以 PNG 格式將圖像輸出
//4. 釋放資源
imageDestroy($im);
畫布管理
imagecreate -- 新建一個基于調(diào)色板的圖像
resource imagecreate ( int x_size, int y_size )
本函數(shù)用來建立空新畫布误辑,參數(shù)為圖片大小旋炒,單位為像素 (pixel)。支持256色脆淹。
imagecreatetruecolor -- 新建一個真彩色圖像
resource imagecreatetruecolor ( int x_size, int y_size )
新建一個真彩色圖像畫布 常空,需要 GD 2.0.1 或更高版本,不能用于 GIF 文件格式盖溺。
imagedestroy -- 銷毀一圖像
bool imagedestroy ( resource image )
imagedestroy() 釋放與 image 關(guān)聯(lián)的內(nèi)存漓糙。
設(shè)置顏色
imagecolorallocate -- 為一幅圖像分配顏色
語法:int imagecolorallocate ( resource image, int red, int green, int blue )
imagecolorallocate() 返回一個標(biāo)識符,代表了由給定的 RGB 成分組成的顏色烘嘱。red昆禽,green 和 blue 分別是所需要的顏色的紅,綠蝇庭,藍(lán)成分醉鳖。這些參數(shù)是 0 到 255 的整數(shù)或者十六進(jìn)制的 0x00 到 0xFF。imagecolorallocate() 必須被調(diào)用以創(chuàng)建每一種用在 image 所代表的圖像中的顏色哮内。
$im = imagecreatetruecolor(100, 100); //創(chuàng)建畫布的大小為100x100
$red = imagecolorallocate($im,255,0,0); //由十進(jìn)制整數(shù)設(shè)置一個顏色
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);// 十六進(jìn)制方式
生成圖片
imagegif -- 以 GIF 格式將圖像輸出到瀏覽器或文件
語法:bool imagegif (resource image [,string filename] )
imagejpeg -- 以 JPEG 格式將圖像輸出到瀏覽器或文件
語法:bool imagejpeg (resource image [,string filename [, int quality]] )
imagepng -- 以 PNG 格式將圖像輸出到瀏覽器或文件
語法:bool imagepng (resource image [,string filename] )
imagewbmp -- 以 WBMP 格式將圖像輸出到瀏覽器或文件
語法:bool imagewbmp (resource image [, string filename [, int foreground]] )
demo.html
<img src="test.php" />
test.php
<?php
//1 創(chuàng)建資源(畫布的大械量谩)
$img = imagecreatetruecolor(200, 200);
//設(shè)置畫布的顏色
$white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF);
$red = imagecolorallocate($img, 255, 0, 0);
$blue = imagecolorallocate($img, 0, 0, 0XFF);
imagefill($img, 0, 0, $white);
//2. 制作各種顏色
imageline($img, 0,0, 200,200, $blue);
imageline($img, 200, 0, 0, 200, $red);
//3. 畫出各種圖形,和寫(畫出)字
//4保存牍蜂,或輸出給瀏覽, 寫第二個參數(shù)就是保存
header("Content-Type:images/gif");
imagegif($img);
//5. 釋放資源
imagedestroy($img);