Note that you can only assign 255 colors to any image palette. If you try assigning more, imagecolorallocate() will fail.
If, for example, you are randomly allocating colors, it will be wise to check if you have used up all of the colors possible. You can use imagecolorclosest() to get the closest assigned color:
<?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);
}
?>
Also, imagecolorallocate() will assign a new color EVERY time the function is called, even if the color already exists in the palette:
<?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); ?>
So here, imagecolorexact() is useful:
<?php
$color = imagecolorexact($pic, $c1, $c2, $c3);
if($color==-1) {
$color = imagecolorallocate($pic, $c1, $c2, $c3);
}
?>
And, for nerdy-ness sake, we can put the two ideas together:
<?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);
}
}
?>
Or as a function:
<?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);
}
?>