Skip to content

Instantly share code, notes, and snippets.

@ericandrewlewis
Created December 14, 2013 05:59
Show Gist options
  • Save ericandrewlewis/7956116 to your computer and use it in GitHub Desktop.
Save ericandrewlewis/7956116 to your computer and use it in GitHub Desktop.
<html>
<head>
<title></title>
</head>
<body>
<?php
/**
* Convert an RGB value to HSL.
*
* @param int $r Red value.
* @param int $g Green value.
* @param int $b Blue value.
* @return array $hsl HSL value in order: hue, saturation, and luminosity.
*/
function rgbToHsl( $r, $g, $b ) {
$oldR = $r;
$oldG = $g;
$oldB = $b;
$r /= 255;
$g /= 255;
$b /= 255;
$max = max( $r, $g, $b );
$min = min( $r, $g, $b );
$h;
$s;
$l = ( $max + $min ) / 2;
$d = $max - $min;
if( $d == 0 ){
$h = $s = 0; // achromatic
} else {
$s = $d / ( 1 - abs( 2 * $l - 1 ) );
switch( $max ) {
case $r:
$h = 60 * fmod( ( ( $g - $b ) / $d ), 6 );
if ($b > $g) {
$h += 360;
}
break;
case $g:
$h = 60 * ( ( $b - $r ) / $d + 2 );
break;
case $b:
$h = 60 * ( ( $r - $g ) / $d + 4 );
break;
}
}
return array( round( $h, 2 ), round( $s, 2 ), round( $l, 2 ) );
}
function get_most_saturated_color_from_image( $path ) {
$img = imagecreatefromjpeg( $path );
$img_size = getimagesize( $path );
$highest_saturation = 0;
for( $row = 0; $row <= $img_size[1]; $row++ ) {
for( $column = 0; $column <= $img_size[0]; $column++ ) {
$rgb = imagecolorat( $img, $row, $column );
$r = ( $rgb >> 16 ) & 0xFF;
$g = ( $rgb >> 8 ) & 0xFF;
$b = $rgb & 0xFF;
$hsl = rgbToHsl( $r, $g, $b );
if ( $hsl[1] > $highest_saturation ) {
if ( $hsl[2] < .3 )
continue;
$pick = array( $r, $g, $b );
}
}
}
$hex = str_pad( dechex( $pick[0] ), 2, '0', STR_PAD_LEFT ) . str_pad( dechex( $pick[1] ), 2, '0', STR_PAD_LEFT ) . str_pad( dechex( $pick[2] ), 2, '0', STR_PAD_LEFT );
return $hex;
}
// $files[] = dirname( __FILE__ ) . '/active.jpg';
$files[] = dirname( __FILE__ ) . '/angkor-wat.jpg';
// $files[] = dirname( __FILE__ ) . '/luxury.jpg';
// $files[] = dirname( __FILE__ ) . '/scotland.jpg';
foreach ( $files as $file ) {
$hex = get_most_saturated_color_from_image( $file );
?>
<div style="height: 100%; width: 100%; background-color: #<?php echo $hex ?>;">
<img src="<?php echo basename( $file ) ?>" /></div><?php
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment