Created
June 24, 2023 21:03
-
-
Save tobiasroeder/705bd1701e553d9d3c6a7981ee4abc41 to your computer and use it in GitHub Desktop.
Get the average color (HEX) from an JPEG image.
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 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