Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This function will get the average colour of an image file using PHP and Image Magick using the IMagick extension.
* 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;
Copy link

kmvan commented Sep 14, 2017

Ur cool man.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment