1

The project i'm working right now require to use some color randomization. I have atleast 20 asset (text,shape,line,polygon ...etc) that require color randomization ...so i decided to store the randomization RGB in a function so i could keep reusing it and make the PHP file smaller but it didn't work out as expected

<?php
header ('Content-Type: image/jpeg'); // make PHP when access .jpg

$im = imagecreatetruecolor(100, 100); // allocate image with 100 width and 100 height
             
function randomrgb() {  
imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255)); // generate 0 between 255
}

$cbc = randomrgb(); // store randomization on variable first  i do not know how to call functions directly 

imagefill($im, 0, 0, $cbc); // fill the background with $cbc which is equal to random RGB function


imagejpeg($im); 
imagedestroy($im);
?>

I expected the background color to become random but it always black also i do not know how to call the function directly here imagefill($im, 0, 0, $cbc); without storing it first on variable something like imagefill( $im, 0, 0, randomrgb(); ); i know it possible but i just do not know how .. sorry in advance if this is confusing

Emma Marshall
  • 354
  • 1
  • 12

1 Answers1

1

In PHP (and many other programming languages) , any variable used inside a function is by default limited to the local function scope .

For your case, please

  1. pass the $im (after you used imagecreatetruecolor to create the image identifier) as parameter to the function; and
  2. add return in your function, so as to assign the result to $cbc

Hence, change to:

<?php
header ('Content-Type: image/jpeg'); // make PHP when access .jpg

$im = imagecreatetruecolor(100, 100); // allocate image with 100 width and 100 height
             
function randomrgb($im) {  
return imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255)); // generate 0 between 255
}

$cbc = randomrgb($im); // store randomization on variable first  i do not know how to call functions directly 

imagefill($im, 0, 0, $cbc); // fill the background with $cbc which is equal to random RGB function


imagejpeg($im); 
imagedestroy($im);
?>
Ken Lee
  • 6,985
  • 3
  • 10
  • 29
  • that's what i'm trying to achive but hmmn you really need to store `randomrgb($im)` on variable first before you can use it on `imagefill` that doesn't save me some space i would just stick on writing `rand()` then i guess almost same logic on what i have but fancier also thank you for explaining and providing example for function return and how it require identifier i would not figure that out – Emma Marshall Sep 03 '22 at 13:25