Last active
February 13, 2023 07:35
-
-
Save Dare-NZ/5544773 to your computer and use it in GitHub Desktop.
A php function that gets the average brightness of an image
This file contains hidden or 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 getAvgLuminance($filename, $num_samples=30) { | |
// needs a mimetype check | |
$img = imagecreatefromjpeg($filename); | |
$width = imagesx($img); | |
$height = imagesy($img); | |
$x_step = intval($width/$num_samples); | |
$y_step = intval($height/$num_samples); | |
$total_lum = 0; | |
$sample_no = 1; | |
for ($x=0; $x<$width; $x+=$x_step) { | |
for ($y=0; $y<$height; $y+=$y_step) { | |
$rgb = imagecolorat($img, $x, $y); | |
$r = ($rgb >> 16) & 0xFF; | |
$g = ($rgb >> 8) & 0xFF; | |
$b = $rgb & 0xFF; | |
// choose a simple luminance formula from here | |
// http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color | |
$lum = ($r+$r+$b+$g+$g+$g)/6; | |
$total_lum += $lum; | |
$sample_no++; | |
} | |
} | |
// work out the average | |
$avg_lum = $total_lum / $sample_no; | |
return ($avg_lum / 255) * 100; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment