Created
December 23, 2013 14:40
-
-
Save paulferrett/8098215 to your computer and use it in GitHub Desktop.
This function will get the average colour of an image file using PHP and Image Magick using the IMagick extension.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the average pixel colour from the given file using Image Magick | |
* | |
* @param string $filename | |
* @param bool $as_hex Set to true, the function will return the 6 character HEX value of the colour. | |
* If false, an array will be returned with r, g, b components. | |
*/ | |
function get_average_colour($filename, $as_hex_string = true) { | |
try { | |
// Read image file with Image Magick | |
$image = new Imagick($filename); | |
// Scale down to 1x1 pixel to make Imagick do the average | |
$image->scaleimage(1, 1); | |
/** @var ImagickPixel $pixel */ | |
if(!$pixels = $image->getimagehistogram()) { | |
return null; | |
} | |
} catch(ImagickException $e) { | |
// Image Magick Error! | |
return null; | |
} catch(Exception $e) { | |
// Unknown Error! | |
return null; | |
} | |
$pixel = reset($pixels); | |
$rgb = $pixel->getcolor(); | |
if($as_hex_string) { | |
return sprintf('%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']); | |
} | |
return $rgb; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ur cool man.