Skip to content

Instantly share code, notes, and snippets.

@dsueiro
Created September 20, 2011 20:43
Show Gist options
  • Select an option

  • Save dsueiro/1230262 to your computer and use it in GitHub Desktop.

Select an option

Save dsueiro/1230262 to your computer and use it in GitHub Desktop.
solid.php
<?php
# Generate solid pgn square
if (count($argv) != 3) die("Bad Format:\nUsage:\tphp gen_image rgb file");
$im = @imagecreate(100, 100)
or die("Cannot Initialize new GD image stream");
$rgb = hex2RGB($argv[1]);
$background_color = imagecolorallocate($im, $rgb['red'], $rgb['green'], $rgb['blue']);
imagepng($im,$argv[2] . '.png');
imagedestroy($im);
function hex2RGB($hexStr, $returnAsString = false, $separator = ',') {
$hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
$rgbArray = array();
if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
$colorVal = hexdec($hexStr);
$rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
$rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
$rgbArray['blue'] = 0xFF & $colorVal;
} elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
$rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
$rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
$rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
} else {
return false; //Invalid hex color code
}
return $returnAsString ? implode($separator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment