Skip to content

Instantly share code, notes, and snippets.

@quisido
Created August 2, 2018 17:08
Show Gist options
  • Save quisido/9c535eb2e73210dc684abc1871ceb993 to your computer and use it in GitHub Desktop.
Save quisido/9c535eb2e73210dc684abc1871ceb993 to your computer and use it in GitHub Desktop.
Creating a Dynamic Vertical Gradient in PHP
<?php
// Validate inputs.
if (
!array_key_exists('from', $_GET) ||
!preg_match('/^[a-fA-F\d]{6}$/', $_GET['from']) ||
!array_key_exists('to', $_GET) ||
!preg_match('/^[a-fA-F\d]{6}$/', $_GET['to']) ||
!array_key_exists('height', $_GET) ||
!is_numeric($_GET['height']) ||
$_GET['height'] < 4 ||
$_GET['height'] > 64
) {
header('HTTP/1.1 404 Not Found');
header('Content-Type: text/plain; charset=utf-8');
exit('Move along. Nothing to see here.');
}
// Calculate start RGB.
$start = Array();
for ($x = 0; $x < 3; $x++)
array_push($start,
stripos('0123456789abcdef',
substr($_GET['from'], $x * 2, 1)
) * 16 +
stripos('0123456789abcdef',
substr($_GET['from'], $x * 2 + 1, 1)
)
);
// Calculate end RGB.
$end = Array();
for ($x = 0; $x < 3; $x++)
array_push($end,
stripos('0123456789abcdef',
substr($_GET['to'], $x * 2, 1)
) * 16 +
stripos('0123456789abcdef',
substr($_GET['to'], $x * 2 + 1, 1)
)
);
// Calculate steps.
$height = $_GET['height'];
$step = Array();
for ($x = 0; $x < 3; $x++)
array_push($step, ($end[$x] - $start[$x]) / $height);
// Generate GIF.
header('Content-Type: image/gif');
$gradient = imagecreatetruecolor(1, $height);
for ($x = 0; $x < $height; $x++)
imagesetpixel(
$gradient,
0, $x,
imagecolorallocate(
$gradient,
$start[0] + $step[0] * $x,
$start[1] + $step[1] * $x,
$start[2] + $step[2] * $x
)
);
imagegif($gradient);
imagedestroy($gradient);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment