Gelform builds Web Applications

Build a color picker palette in php

For ages, I’ve been looking for a script that will output a range of hex colors that I can use to design my own color picker pallet. You know, those circles that have every color. Only I prefer steps, not infinite options.

From this Stack Overflow answer, I created a function that will generate an array of hex colors, stepping between two hex colors.

function list_colours($start, $end, $steps = 6)
{
	$return = array();

	$start_r = hexdec(substr($start, 1, 2));
	$start_g = hexdec(substr($start, 3, 2));
	$start_b = hexdec(substr($start, 5, 2));

	$end_r = hexdec(substr($end, 1, 2));
	$end_g = hexdec(substr($end, 3, 2));
	$end_b = hexdec(substr($end, 5, 2));

	$shift_r = ($end_r - $start_r) / $steps;
	$shift_g = ($end_g - $start_g) / $steps;
	$shift_b = ($end_b - $start_b) / $steps;

	for ($i = 0; $i < $steps; $i++)
	{
		$color = array();
		$color[] = dechex($start_r + ($i * $shift_r));
		$color[] = dechex($start_g + ($i * $shift_g));
		$color[] = dechex($start_b + ($i * $shift_b));

		// Pad with zeros.
		$color = array_map(function ($item) {
				return str_pad($item, 2, "0", STR_PAD_LEFT);
			},
			$color
		);

		$return[] = '#' . implode($color);
	}

	return $return;
}

$spectrum = array();
$spectrum[] = list_colours("#000000", "#FFFFFF"); // grey
$spectrum[] = list_colours("#cc0033", "#FFFFFF"); // R
$spectrum[] = list_colours("#ff6600", "#FFFFFF"); // O
$spectrum[] = list_colours("#fdc710", "#FFFFFF"); // Y
$spectrum[] = list_colours("#cccc00", "#FFFFFF"); // G
$spectrum[] = list_colours("#339933", "#FFFFFF"); // G dark
$spectrum[] = list_colours("#339999", "#FFFFFF"); // B teal
$spectrum[] = list_colours("#14acde", "#FFFFFF"); // B light
$spectrum[] = list_colours("#0066cc", "#FFFFFF"); // B dark
$spectrum[] = list_colours("#663399", "#FFFFFF"); // I dark
$spectrum[] = list_colours("#990066", "#FFFFFF"); // I light
$spectrum[] = list_colours("#cc0066", "#FFFFFF"); // V pink

To output an SVG, use this code:

	<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 145 295">
		<?php $y = 10; foreach ($spectrum as $arr ) : $x = 10;
			foreach ($arr as $i => $hex ) :
				?>
				<circle cx="<?php echo $x ?>" cy="<?php echo $y ?>" r="10" style="fill:<?php echo $hex ?>"/>
				<?php $x += 22; endforeach; ?>
			<?php $y += 22; endforeach; ?>
	</svg>

Outputs color picker pallete

← Blog