php 用圖片處理函數(shù)畫一張圖
一起來看看下面有一張圖:
#我們該怎麼把這張圖畫出來呢。
我們可以依照步驟分析:
????1.繪圖
????2.準備繪製這張圖所需要的顏色
????3.填入背景顏色
????4.畫出兩個對角線
????5.圓形
????6.在圓形上方畫一個矩型
????7.保存圖片
????8.銷毀資源
#一、我們依照這張圖推出步驟。我們來分析需要使用到的函數(shù):
//使用imagecreate函數(shù)創(chuàng)建圖片,返回資源 $img = imagecreate(500,500);
二、圖片建立完成我們需要填入圖片資源顏色,需要使用到函數(shù)
$顏色變量 = imagecolorallocate ( resource $圖片資源 , int $紅 , int $綠 , int $藍 )
紅、綠、藍是電腦裡面操作圖片的三個基本色。由這三種顏色來組合成我們?nèi)庋鬯吹降乃蓄伾?
因此 imagecolorallocate 先輸入圖片資源,操作這個資源。為這個圖片資源準備顏色。
就相當於在畫畫的時候,先把畫布準備好,再準備顏料。
根據(jù)這張圖,我們要準備出來的顏色有:
????1.綠色
????2.藍色
????3.黑色
#????3.黑色
????4.棕色
依照電腦的配色原則分配的話,我們下面的顏色分配的程式碼就要寫成下面的樣子://紅
$red = imagecolorallocate($img, 255, 0, 0);
//綠
$green = imagecolorallocate($img, 0, 255, 0);
//藍
$blue = imagecolorallocate($img, 0, 0, 255);
//棕
$yellow = imagecolorallocate($img, 121, 72, 0);
這中圖片中需要用到的幾個顏色的色值。
三、 將顏色加到背景進行填充
imagefilledrectangle ( resource $圖片資源 , int $點1x軸, int $點1y軸 , int $點2x軸 , int $點2y軸 , int $color )
這個函數(shù)需要涉及到幾何的一點點知識。
????1.一個點由x 座標和y 座標組成一個點
????2.兩個點可以組成直線
如下圖:
點1 為x軸為畫布的0位置,點1的y軸也為畫布的0位置。 點2 為x軸為畫布的500位置,點2的y軸也為畫布的500位置。
四、畫兩條對角線
imageline($img, 0, 0, 500, 500, $red); imageline($img, 500, 0, 0, 500, $blue);
五、在上面畫一個圓
bool imagefilledellipse ( resource $圖片資源 , int $圓心x , int $圓心y , int $圓的寬 , int $圓的高 , int $圓的顏色 ) imagefilledellipse($img, 250, 250, 200, 200, $yellow);
操作這個資源,寫上圓心的座標。然後寫上長和寬。若長寬一致為正圓,則不一致則為橢圓。
六、在圓上面畫一個矩型
imagefilledrectangle($img, 200, 200, 300, 300, $blue);
這個我們在上面一個講過,我們就不細說了。
七、儲存圖片
bool imagejpeg ( resource $image [, string $filename])
#八、銷毀圖片資源
imagedestroy($img);
我們來看看最終組合出來的程式碼:
<?php //創(chuàng)建圖片 $img = imagecreatetruecolor(500, 500); //分配顏色 $red = imagecolorallocate($img, 255, 0, 0); $green = imagecolorallocate($img, 0, 255, 0); $blue = imagecolorallocate($img, 0, 0, 255); $pur = imagecolorallocate($img, 255, 0, 255); $yellow = imagecolorallocate($img, 121, 72, 0); //填充背景 imagefilledrectangle($img, 0, 0, 500, 500, $green); //畫對角線 imageline($img, 0, 0, 500, 500, $red); imageline($img, 500, 0, 0, 500, $blue); //畫圓 imagefilledellipse($img, 250, 250, 200, 200, $yellow); //圓中間畫矩形 imagefilledrectangle($img, 200, 200, 300, 300, $blue); //保存圖片,圖片名為haha.jpg imagejpeg($img, 'haha.jpg'); //銷毀資源 imagedestroy($img); ?>