Skip to content

Instantly share code, notes, and snippets.

@gido
Created December 13, 2010 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gido/738981 to your computer and use it in GitHub Desktop.
Save gido/738981 to your computer and use it in GitHub Desktop.
Example of a simple script to manipulate hexadecimal color
<?php
$input = "#A2D73A";
if(!preg_match('/#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})/', $input, $matches)){
die(sprintf("Error: '%s' is not a valid hexadecimal color!", $input));
}
$bgColor1 = $input;
$bgColor2 = blackify($input, 60);
$bgColor3 = blackify($input, 100);
$bgColor4 = blackify($input, 150);
/**
* Reduce red, green and blue color
*
* @param string $hexaString (format: #FFAA33)
* @param integer $increment
*/
function blackify($hexaString, $inc) {
if(!preg_match('/#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})/', $hexaString, $matches)){
return false;
}
list(, $red, $green, $blue) = $matches;
$red = intval($red, 16);
$green = intval($green, 16);
$blue = intval($blue, 16);
$red2 = ($red - $inc);
$green2 = ($green - $inc);
$blue2 = ($blue - $inc);
// keept value in range 0..255
$red2 = $red2 > 255 ? 255 : ($red2 < 0 ? 0 : $red2);
$green2 = $green2 > 255 ? 255 : ($green2 < 0 ? 0 : $green2);
$blue2 = $blue2 > 255 ? 255 : ($blue2 < 0 ? 0 : $blue2);
return sprintf("#%02x%02x%02x", $red2, $green2, $blue2);
}
?><!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<title>hexa color test</title>
<meta name="description" content="">
<meta name="author" content="Gilles Doge">
<style type="text/css" media="screen">
.block{
display: block;
float: left;
height: 150px;
width: 150px;
border: 1px solid #f0f0f0;
margin: 50px 50px 10px 20px;
text-align: center;
padding: 20px;
}
</style>
</head>
<body>
<div id="container">
<div id="main">
<div id="block1" class="block" style="background-color: <?php echo $bgColor1; ?>">block 1</div>
<div id="block2" class="block" style="background-color: <?php echo $bgColor2; ?>">block 2</div>
<div id="block3" class="block" style="background-color: <?php echo $bgColor3; ?>">block 3</div>
<div id="block4" class="block" style="background-color: <?php echo $bgColor4; ?>">block 4</div>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment