Help - Getting RGB values in an image

Okay, I’m using the following code as an API which should echo a JSON table with each pixel’s RGB value inside, G, B).

	if (array_key_exists('Image',$_GET)) {
		$Image = $_GET["Image"];
		$File = file_get_contents($Image);
		$Colors = array();
		list($width, $height) = getimagesize($File);
		function AddToArray($X, $Y){
			$rgb = imagecolorat($File, $X, $Y);
			$r = ($rgb >> 16) & 0xFF;
			$g = ($rgb >> 8) & 0xFF;
			$b = $rgb & 0xFF;
			$Colors[] = "" + $r + ", " + $g + ", " + $b + ")";
		$IX = 0;
		$IY = 0;
		while($IX <= $width and $IY <= $height){
			AddToArray($IX, $IY);
			$IX = $IX + 1;
			$IY = $IY + 1;
		echo json_encode($Colors);

For some reason, it echoes an empty table. Could someone please help me by explaining what im doing wrong. Im a beginner at PHP. Thanks.

I believe the problem is to do with actually finding the image but if that is the case, I do not know how to fix it.

You need to declare $Colors as a global if you want to use it inside your function. If you don’t, it will just create a local array inside the function, and lose it when the function exits. In the same way that your $rgb, $r, $g, and $b variables are local and don’t exist outside the function, so is the array that you reference.

Have a read up on variable scope:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.