請注意,您只能將 255 種顏色指派給任何影像調色盤。如果您嘗試指派更多顏色,imagecolorallocate() 將會失敗。
舉例來說,如果您是隨機配置顏色,最好檢查您是否已用盡所有可能的顏色。您可以使用 imagecolorclosest() 來取得最接近的已指派顏色。
<?php
$c1 = mt_rand(50,200); $c2 = mt_rand(50,200); $c3 = mt_rand(50,200); if(imagecolorstotal($pic)>=255) {
$color = imagecolorclosest($pic, $c1, $c2, $c3);
} else {
$color = imagecolorallocate($pic, $c1, $c2, $c3);
}
?>
此外,imagecolorallocate() 會在每次呼叫函式時指派新的顏色,即使該顏色已存在於調色盤中也是如此。
<?php
imagecolorallocate($pic,125,125,125); imagecolorallocate($pic,125,125,125); imagecolorallocate($pic,125,125,125); imagecolorallocate($pic,125,125,125); imagecolorallocate($pic,125,125,125); ?>
因此,在這裡,imagecolorexact() 會很有用。
<?php
$color = imagecolorexact($pic, $c1, $c2, $c3);
if($color==-1) {
$color = imagecolorallocate($pic, $c1, $c2, $c3);
}
?>
為了滿足技術宅的樂趣,我們可以將這兩個概念結合起來
<?php
$c1 = mt_rand(50,200); $c2 = mt_rand(50,200); $c3 = mt_rand(50,200); $color = imagecolorexact($pic, $c1, $c2, $c3);
if($color==-1) {
if(imagecolorstotal($pic)>=255) {
$color = imagecolorclosest($pic, $c1, $c2, $c3);
} else {
$color = imagecolorallocate($pic, $c1, $c2, $c3);
}
}
?>
或者以函式的方式呈現
<?php
function createcolor($pic,$c1,$c2,$c3) {
$color = imagecolorexact($pic, $c1, $c2, $c3);
if($color==-1) {
if(imagecolorstotal($pic)>=255) {
$color = imagecolorclosest($pic, $c1, $c2, $c3);
} else {
$color = imagecolorallocate($pic, $c1, $c2, $c3);
}
}
return $color;
}
for($i=0; $i<1000; $i++) { $c1 = mt_rand(50,200); $c2 = mt_rand(50,200); $c3 = mt_rand(50,200); $color = createcolor($pic,$c1,$c2,$c3);
}
?>