在之前的文章中給大家?guī)砹恕禤HP中怎么輸出圖片?(圖例詳解)》,其中詳細(xì)介紹了應(yīng)該怎樣在PHP中輸出圖片,本篇文章繼續(xù)給大家?guī)砦覀儜?yīng)該怎樣在PHP中繪制圖像,希望能夠幫助到大家!
在PHP中繪制圖像一切還是基于上一篇文章中的畫布,創(chuàng)建畫布,然后在畫布上進(jìn)行繪制圖像。想到圖像我們就想到了色彩,所以首先,我們來看一下,我們應(yīng)該怎樣在PHP中給圖像定義顏色。
圖像定義顏色
在我們使用PHP進(jìn)行圖像操作時(shí),必然離不開的就是顏色的設(shè)置,不同的顏色勾勒出了這漂亮的圖像。那么在PHP中我們應(yīng)該怎樣給圖像來提供顏色呢?這時(shí)候我們就要用到imagecolorallocate() 和 imagecolorallocatealpha()這兩個(gè)函數(shù)。接下來,我們就來看一看應(yīng)該怎樣使用這兩個(gè)函數(shù)。
-
imagecolorallocate()
函數(shù)
imagecolorallocate() 函數(shù)能夠?yàn)閳D像分配顏色,想要設(shè)置多種顏色的話,需要多次調(diào)用該函數(shù),函數(shù)的語法格式:
imagecolorallocate(resource $image, int $red, int $green, int $blue)
其中,$image表示了需要設(shè)置顏色的圖像,該函數(shù)會(huì)返回一個(gè)標(biāo)識(shí)符,表示了給定的RGB成分組成的顏色,$red,$green 和 $blue 分別是所需要的顏色的紅,綠,藍(lán)成分,取值范圍是 0 到 255 的整數(shù)或者十六進(jìn)制的 0x00 到 0xFF。
示例如下:
<?php $image = imagecreate(100, 100); $blue = imagecolorallocate($image, 0, 0, 255); header('Content-type:image/jpeg'); imagejpeg($image); imagedestroy($image); ?>
輸出結(jié)果:
-
imagecolorallocatealpha()
函數(shù)
imagecolorallocatealpha()函數(shù)與imagecolorallocate()函數(shù)相比,它們的作用是相同的,但是多了一個(gè)用來設(shè)置透明參數(shù)的alpha,它的語法格式如下:
imagecolorallocatealpha(resource $image, int $red, int $green, int $blue, int $alpha)
其中,前面的參數(shù)與imagecolorallocate()函數(shù)的參數(shù)表示為一致的,$alphab表示的是透明度的參數(shù),取值范圍在 0 到 127 之間,0 表示完全不透明,127 則表示完全透明。
示例如下:
<?php $size=300; $image=imagecreatetruecolor($size,$size); $back=imagecolorallocate($image,0,0,0); $border=imagecolorallocate($image,255,255,255); imagefilledrectangle($image,0,0,$size-1,$size-1,$back); imagerectangle($image,0,0,$size-1,$size-1,$border); $yellow_x=100; $yellow_y=75; $red_x=100; $red_y=165; $blue_x=187; $blue_y=125; $radius=150; //用alpha值分配一些顏色 $yellow=imagecolorallocatealpha($image,200,200,0,75); $red=imagecolorallocatealpha($image,200,0,0,75); $blue=imagecolorallocatealpha($image,0,0,200,75); //畫3個(gè)交迭的圓 imagefilledellipse($image,$yellow_x,$yellow_y,$radius,$radius,$yellow); imagefilledellipse($image,$red_x,$red_y,$radius,$radius,$red); imagefilledellipse($image,$blue_x,$blue_y,$radius,$radius,$blue); //不要忘記輸出正確的header! header('Content-type:image/png'); //最后輸出結(jié)果 imagepng($image); imagedestroy($image); ?>
輸出結(jié)果:
由此通過imagecolorallocate() 和 imagecolorallocatealpha()這兩個(gè)函數(shù)已經(jīng)能夠?qū)崿F(xiàn)在圖像上定義顏色了。同時(shí)圖像不僅是由顏色構(gòu)成的,還需要有點(diǎn)、線還有不同的形狀。那接下來我們來看一看,應(yīng)該怎樣去解決這些問題。
繪制點(diǎn)和線
繪制點(diǎn)和線可以說是PHP中繪制圖像最基本的操作了,雖然很基本,但是靈活應(yīng)用起來,可以通過它們繪制出