Skip to content

Instantly share code, notes, and snippets.

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 w33zy/09b4f8fdb6e0bc7c1679b7ddb9cbd916 to your computer and use it in GitHub Desktop.
Save w33zy/09b4f8fdb6e0bc7c1679b7ddb9cbd916 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.
<?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