So, I googled how to create an image gradient in php. The idea is that, you define the start and end color, and define a step size of $stepSize = ($end-$start)/($imgHeight)
. You make a for loop, and in each step of the loop, create a 1 pixel tall rectangle that is as wide the image, and set its color to $start+$i*$stepSize
. That idea, and code, I found here:
http://www.geekthis.net/blog/87/php-gradient-images-rectangle-gd
That code creates a new image of a linear gradient. For your situation, I ran with that basic idea: Shave off 1 pixel rows from your source image, and IMG_FILTER_COLORIZE
each row to the color of the gradient.
Here is the code:
<?php
//move alpha preserving code to its own function
//since it is used several times
function preserveAlpha(&$img) {
$background = imagecolorallocate($img, 0, 0, 0);
imagecolortransparent($img, $background);
imagealphablending($img, false);
imagesavealpha($img, true);
}
$img = imagecreatefrompng('splat-base.png');
preserveAlpha($img);
//grab width and height
$width = imagesx($img);
$height = imagesy($img);
//the final image
$final = imagecreatetruecolor($width, $height);
preserveAlpha($final);
//start and end values of the gradient
$start = $_GET['start'];
$end = $_GET['end'];
//convert 3 color codes to 6
if (strlen($start) == 3) {
$start = $start[0] . $start[0] . $start[1] . $start[1] . $start[2] . $start[2];
}
if (strlen($end) == 3) {
$end = $end[0] . $end[0] . $end[1] . $end[1] . $end[2] . $end[2];
}
//make sure the lighter color is first
$starthex = intval($start, 16);
$endhex = intval($end, 16);
if ($endhex > $starthex) {
//then we need to flip
$temp = $end;
$end = $start;
$start = $temp;
}
//convert from hex to rgb
$s = array(
hexdec(substr($start, 0, 2)),
hexdec(substr($start, 2, 2)),
hexdec(substr($start, 4, 2))
);
$e = array(
hexdec(substr($end, 0, 2)),
hexdec(substr($end, 2, 2)),
hexdec(substr($end, 4, 2))
);
//the for loop. go through each 1 pixel row of the image,
//shave it off, apply a filter, and append it to our new image
for ($i = 0; $i < $height; $i++) {
//grab the $ith row off of the image
$pixelRow = imagecreatetruecolor($width, 1);
preserveAlpha($pixelRow);
imagecopy($pixelRow, $img, 0, 0, 0, $i, $width, 1);
//calculate the next color in the gradient
$r = intval($s[0] - ((($s[0] - $e[0]) / $height) * $i));
$g = intval($s[1] - ((($s[1] - $e[1]) / $height) * $i));
$b = intval($s[2] - ((($s[2] - $e[2]) / $height) * $i));
//apply the filter
imagefilter($pixelRow, IMG_FILTER_COLORIZE, $r - 255, $g, $b);
//append it to our new iamge
imagecopy($final, $pixelRow, 0, $i, 0, 0, $width, 1);
}
header('Content-Type: image/png');
imagepng($final);
/* Some Cleanup */
imagedestroy($final);
exit;
?>