Search
 
SCRIPT & CODE EXAMPLE
 

PHP

php convert hex to rgba

/**
 * Convert hexadecimal string to rgba output
 * @param string $hex_color
 * @return string
 */
function hex2rgba(string $hex_color):string
{
	// Remove '#' from the input
	$hex_color = str_replace('#', '', $hex_color);
	// Return black if provided color isn't 3, 4, 6, or 8 characters
	if ( !in_array(strlen($hex_color), [3,4,6,8]) ) {
		return 'rgb(0,0,0,1)';
	}
	// If using 3 or 4 character shorthand, convert to full
	if ( strlen($hex_color) <= 4 ) {
		// Split into array of single characters
		$hex_arr = str_split($hex_color);
		// Double each character
		$hex_arr = array_map(fn($c) => $c[0] . $c[0], $hex_arr);
	} else {
		// Split into array of character couplets
		$hex_arr = str_split($hex_color, 2);
	}
	// If only three groups, add opaque alpha group
	if ( count($hex_arr) === 3 ) {
		$hex_arr[] = 'ff';
	}
	// Apply hexadecimal to decimal conversion on each couplet
	$dec_arr = array_map('hexdec', $hex_arr);
	// Divide the alpha channel by 255 (converts to 0...1)
	$dec_arr[3] /= 255;
	// Glue the pieces back together and return inside 'rgba()'
	return 'rgba(' . implode(",", $dec_arr) . ')';
}
Comment

PREVIOUS NEXT
Code Example
Php :: php timestamp format 
Php :: php get index of current item array_reduce 
Php :: Too Many Attempts. laravel error 
Php :: php remove object from array by property 
Php :: laravel php artisan make:controller in subfolder 
Php :: Creating a Basic Route in Laravel 8 
Php :: laravel db::query update 
Php :: php get all url parameters 
Php :: laravel validation allow empty array 
Php :: concat and search in laravel eloquent 
Php :: composer clear cache 
Php :: pdo get row count 
Php :: convert string to lowercase in php 
Php :: smtp server xampp 
Php :: php remove charictors from a string 
Php :: show query in laravel 
Php :: remove first element in array php 
Php :: laravel hasfile 
Php :: global laravel request() 
Php :: sanitize user input php 
Php :: cache clear in laravel 
Php :: php permanent redirect to url 
Php :: read-json-data-response-using-php 
Php :: check if the form is submitted php 
Php :: how to create a logfile in php? 
Php :: delete method laravel 
Php :: php json_decode without quotes 
Php :: how to force delete in laravel 8 
Php :: Allowed memory size of 1610612736 bytes exhausted laravel 
Php :: how get role of user in laravel spatie 
ADD CONTENT
Topic
Content
Source link
Name
4+8 =