設(shè)置畫布顏色的方法:1、使用“imagecolorallocate(image,red,green,blue)”語句;2、使用“imagecolorallocatealpha(image,red,green,blue,alpha)”語句。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦
方法1:imagecolorallocate() 函數(shù)
imagecolorallocate() 函數(shù)可以為一個(gè)圖像資源分配顏色,如果在圖像中需要設(shè)置多種顏色,只要多次調(diào)用該函數(shù)即可。函數(shù)的語法格式如下所示:
imagecolorallocate(resource $image, int $red, int $green, int $blue):
其中,$image 為要設(shè)置顏色的圖像資源,imagecolorallocate() 函數(shù)會(huì)返回一個(gè)標(biāo)識(shí)符,代表了由給定的 RGB 成分組成的顏色;$red,$green 和 $blue 分別是所需要的顏色的紅,綠,藍(lán)成分,取值范圍是 0 到 255 的整數(shù)或者十六進(jìn)制的 0x00 到 0xFF。
提示:如果是使用 imagecreate() 函數(shù)創(chuàng)建的圖像資源,在第一次調(diào)用 imagecolorallocate() 函數(shù)時(shí)會(huì)默認(rèn)為其填充背景色。
【示例】使用 imagecolorallocate() 函數(shù)為圖像設(shè)置顏色。
<?php $image = imagecreate(100, 100); $blue = imagecolorallocate($image, 0, 0, 255); $red = imagecolorallocate($image, 255, 0, 0); $green = imagecolorallocate($image, 0, 255, 0); header('Content-type:image/jpeg'); imagejpeg($image); imagedestroy($image); ?>
運(yùn)行結(jié)果如下圖所示:
方法2:使用imagecolorallocatealpha() 函數(shù)
imagecolorallocatealpha() 函數(shù)的作用和 imagecolorallocate() 相同,但多了一個(gè)額外的設(shè)置透明度的參數(shù) alpha,函數(shù)的語法格式如下:
imagecolorallocatealpha(resource $image, int $red, int $green, int $blue, int $alpha)
其中,$image 為要設(shè)置顏色的圖像資源;$red,$green 和 $blue 分別是所需要的顏色的紅,綠,藍(lán)成分,取值范圍是 0 到 255 的整數(shù)或者十六進(jìn)制的 0x00 到 0xFF;$alpha 用來設(shè)置顏色的透明的,取值范圍在 0 到 127 之間,0 表示完全不透明,127 則表示完全透明。
【示例】使用 imagecolorallocatealpha() 函數(shù)為圖像設(shè)置顏色。
<?php $size=300; $image=imagecreatetruecolor($size,$size); //用白色背景加黑色邊框畫個(gè)方框 $back=imagecolorallocate($image,255,255,255); $border=imagecolorallocate($image,0,0,0); 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=120; $red_y=165; $blue_x=187; $blue_y=125; $radius=150; //用alpha值分配一些顏色 $yellow=imagecolorallocatealpha($image,255,255,0,75); $red=imagecolorallocatealpha($image,255,0,0,75); $blue=imagecolorallocatealpha($image,0,0,255,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); ?>
運(yùn)行結(jié)果如下圖所示:
推薦學(xué)習(xí):《PHP視頻教程》