I've made this code to get hex colors of the first pixel and the last pixel of an image. The code for the first pixel is working, I get the HEX code. But for the last pixel, I've an error:
PHP Notice: imagecolorat(): 1,1024 is out of bounds in /var/playground/imghex.php on line 55
Here's my code:
$gradientHeight = getimagesize($res["gradient"]);
// get Positions
$im = imagecreatefrompng($res["gradient"]);
$rgb = imagecolorat($im, 0, 0);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
// store
$res["Gradient1"] = rgb2hex([$r, $g, $b]);
// get positions
print_r($gradientHeight);
$rgb2 = imagecolorat($im, $gradientHeight[0], $gradientHeight[1]);
$r2 = ($rgb2 >> 16) & 0xFF;
$g2 = ($rgb2 >> 8) & 0xFF;
$b2 = $rgb2 & 0xFF;
// store
$res["Gradient2"] = rgb2hex([$r2, $g2, $b2]);
// print
print_r($res);
What's wrong? I don't see any error
You see that notice because you are using the size on a 0-based index. If you have size of 1024
, you'll have positions from 0
to 1023
.
That way, you'll need to subtract 1
from it. Replace
$rgb2 = imagecolorat($im, $gradientHeight[0], $gradientHeight[1]);
with
$rgb2 = imagecolorat($im, $gradientHeight[0] - 1, $gradientHeight[1] - 1);