Skip to content

Instantly share code, notes, and snippets.

@mrl22
Created October 23, 2023 16:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrl22/faacd7bd534f68cb97e3a27a5b547684 to your computer and use it in GitHub Desktop.
Save mrl22/faacd7bd534f68cb97e3a27a5b547684 to your computer and use it in GitHub Desktop.
Laravel / PHP - Check if a hexidecimal colour is dark
<?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