Skip to content

Instantly share code, notes, and snippets.

@microinginer
Last active August 15, 2022 21:31
Show Gist options
  • Save microinginer/1e6c86b3121ac7ad7caedb881b41149b to your computer and use it in GitHub Desktop.
Save microinginer/1e6c86b3121ac7ad7caedb881b41149b to your computer and use it in GitHub Desktop.
<?php
function resizeImage($image, $origWidth, $origHeight, $maxWidth, $maxHeight)
{
if ($maxWidth === 0) {
$maxWidth = $origWidth;
}
if ($maxHeight === 0) {
$maxHeight = $origHeight;
}
$widthRatio = $maxWidth / $origWidth;
$heightRatio = $maxHeight / $origHeight;
$ratio = min($widthRatio, $heightRatio);
$newWidth = (int)$origWidth * $ratio;
$newHeight = (int)$origHeight * $ratio;
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
return [
'image' => $newImage,
'width' => $newWidth,
'height' => $newHeight,
];
}
// http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
function getLum($filename)
{
try {
list($width, $height, $type) = getimagesize($filename);
switch ($type) {
case IMAGETYPE_PNG:
$img = imagecreatefrompng($filename);
break;
default:
$img = imagecreatefromjpeg($filename);
break;
}
$height /= 2;
$area = ["x" => 0, "y" => $height, "width" => $width, "height" => $height];
$img = imagecrop($img, $area);
$result = resizeImage($img, $width, $height, 500, 500);
$img = $result['image'];
$width = $result['width'];
$height = $result['height'];
$totalLum = 0;
$sampleNo = 1;
for ($x = 0; $x < $width; $x += 2) {
for ($y = 0; $y < $height; $y += 2) {
$rgb = imagecolorat($img, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$lum = ($r + $r + $b + $g + $g + $g) / 6;
$totalLum += $lum;
$sampleNo++;
}
}
$avgLum = $totalLum / $sampleNo;
$res = ($avgLum / 255) * 100;
return [
'lum' => $res < 30 ? 0 : 1,
'factor' => $res,
'error' => '',
];
} catch (Exception $exception) {
return [
'lum' => '',
'factor' => '',
'error' => $exception->getMessage(),
];
}
}
$startTime = microtime(true);
print_r(getLum('./big.jpeg')) . PHP_EOL;
echo microtime(true) - $startTime . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment