Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP function to convert Hex to HSL
In PHP, you can convert hex color values to HSL (Hue, Saturation, Lightness) format using a custom function. HSL is useful for color manipulation and provides a more intuitive way to work with colors compared to hex values.
Function to Convert Hex to HSL
The following function converts a hex color code to HSL values −
<?php
function hex_To_Hsl($hex) {
// Remove # if present
$hex = ltrim($hex, '#');
// Split hex into RGB components
$hex_val = array(substr($hex, 0, 2), substr($hex, 2, 2), substr($hex, 4, 2));
// Convert to decimal and normalize (0-1)
$rgb_val = array_map(function($part) {
return hexdec($part) / 255;
}, $hex_val);
$max_val = max($rgb_val);
$min_val = min($rgb_val);
$l = ($max_val + $min_val) / 2;
if ($max_val == $min_val) {
$h = $s = 0; // achromatic
} else {
$diff = $max_val - $min_val;
$s = $l > 0.5 ? $diff / (2 - $max_val - $min_val) : $diff / ($max_val + $min_val);
switch($max_val) {
case $rgb_val[0]:
$h = ($rgb_val[1] - $rgb_val[2]) / $diff + ($rgb_val[1] < $rgb_val[2] ? 6 : 0);
break;
case $rgb_val[1]:
$h = ($rgb_val[2] - $rgb_val[0]) / $diff + 2;
break;
case $rgb_val[2]:
$h = ($rgb_val[0] - $rgb_val[1]) / $diff + 4;
break;
}
$h /= 6;
}
return array(
round($h * 360), // Hue in degrees (0-360)
round($s * 100), // Saturation in percentage (0-100)
round($l * 100) // Lightness in percentage (0-100)
);
}
// Example usage
$hex_color = "#FF5733";
$hsl = hex_To_Hsl($hex_color);
echo "Hex: $hex_color<br>";
echo "HSL: H={$hsl[0]}°, S={$hsl[1]}%, L={$hsl[2]}%<br>";
// Test with more colors
$colors = array("#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#000000");
foreach($colors as $color) {
$hsl = hex_To_Hsl($color);
echo "$color ? H={$hsl[0]}°, S={$hsl[1]}%, L={$hsl[2]}%<br>";
}
?>
Hex: #FF5733 HSL: H=9°, S=100%, L=60% #FF0000 ? H=0°, S=100%, L=50% #00FF00 ? H=120°, S=100%, L=50% #0000FF ? H=240°, S=100%, L=50% #FFFFFF ? H=0°, S=0%, L=100% #000000 ? H=0°, S=0%, L=0%
How It Works
The conversion process involves these steps:
- Parse Hex: Split the 6-character hex code into RGB components
- Normalize RGB: Convert hex values to decimal and divide by 255
- Calculate Lightness: Average of max and min RGB values
- Calculate Saturation: Based on the difference between max and min values
- Calculate Hue: Determined by which RGB component has the maximum value
Conclusion
This function provides an accurate conversion from hex to HSL format, returning hue in degrees (0-360) and saturation/lightness as percentages (0-100). HSL values are particularly useful for color manipulation and creating color schemes.
Advertisements
