Last active
March 4, 2018 00:43
-
-
Save march1993/218a088d9019a97902b5183501b1d33c to your computer and use it in GitHub Desktop.
PHP get dominant color
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 | |
function get_featured_color() { | |
/* Here is an example for wordpress, replace $filepath in your situation. */ | |
$post_thumbnail_id = get_post_thumbnail_id(); | |
$filepath = get_attached_file($post_thumbnail_id); | |
$im = imagecreatefromstring(file_get_contents($filepath)); | |
$nx = imagesx($im); | |
$ny = imagesy($im); | |
/* Calculate only for the center part of the image. */ | |
$sx = (int) ($nx * 0.4); | |
$ex = (int) ($nx * 0.6); | |
$sy = (int) ($ny * 0.4); | |
$ey = (int) ($ny * 0.6); | |
/* Down sample to around 100 X 100 */ | |
$step = (int) (($ex - $sx) / 100); | |
$step = $step > 1 ? $step : 1; | |
$R = 0; | |
$G = 0; | |
$B = 0; | |
$c = 0; | |
for ($x = $sx; $x < $ex; $x += $step) { | |
for ($y = $sy; $y < $ey; $y += $step) { | |
$rgb = imagecolorat($im, $x, $y); | |
$r = ($rgb >> 16) & 0xFF; | |
$g = ($rgb >> 8) & 0xFF; | |
$b = $rgb & 0xFF; | |
$R += $r; | |
$G += $g; | |
$B += $b; | |
$c += 1; | |
} | |
} | |
if ($c !== 0) { | |
return sprintf('#%02x%02x%02x', (int) ($R / $c), (int) ($G / $c), (int) ($B / $c)); | |
} else { | |
/* Fallback color */ | |
return '#e2eb88'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment