Skip to content

Instantly share code, notes, and snippets.

@tobiasroeder
Created June 24, 2023 21:03
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 tobiasroeder/705bd1701e553d9d3c6a7981ee4abc41 to your computer and use it in GitHub Desktop.
Save tobiasroeder/705bd1701e553d9d3c6a7981ee4abc41 to your computer and use it in GitHub Desktop.
Get the average color (HEX) from an JPEG image.
<?php
/**
* Get the average color from an JPEG image.
*
* @param string $image_path Explicit path to the image.
*
* @return string Returns a HEX value.
*/
function average_color(string $image_path): string
{
$image = imagecreatefromjpeg($image_path);
$tmp_image = imagecreatetruecolor(1, 1);
$x = imagesx($image);
$y = imagesy($image);
imagecopyresampled($tmp_image, $image, 0, 0, 0, 0, 1, 1, $x, $y);
$rgb = imagecolorat($tmp_image, 0, 0);
$red = ($rgb >> 16) & 0xff;
$green = ($rgb >> 8) & 0xff;
$blue = $rgb & 0xff;
$hex = sprintf('#%02x%02x%02x', $red, $green, $blue);
return $hex;
}
/**
* Example code.
*/
$image_path = '/path/to/image.jpeg';
$average_color = average_color($image_path);
echo $average_color;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment