Created
October 23, 2023 16:38
-
-
Save mrl22/faacd7bd534f68cb97e3a27a5b547684 to your computer and use it in GitHub Desktop.
Laravel / PHP - Check if a hexidecimal colour is dark
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 | |
namespace App\Helpers; | |
class ColorHelper | |
{ | |
// This function tell you if a color is dark or light. | |
// It is useful when you want to change the text color to white or black depending on the background color. | |
public static function isColorDark($hexColor = '#ffffff') { | |
// Remove any hash symbol (#) if present | |
$hexColor = str_replace('#', '', $hexColor); | |
// Check if color is valid hex color | |
if (!preg_match('/^[a-f0-9]{6}$/i', $hexColor)) | |
return false; | |
// Convert hex to RGB | |
$r = hexdec(substr($hexColor, 0, 2)); | |
$g = hexdec(substr($hexColor, 2, 2)); | |
$b = hexdec(substr($hexColor, 4, 2)); | |
// Calculate color brightness | |
$brightness = (($r * 299) + ($g * 587) + ($b * 114)) / 1000; | |
// You can adjust this threshold as needed | |
$threshold = 128; | |
return $brightness < $threshold; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!