color-utils
color-utils copied to clipboard
hex() helper function
What about adding a hex() helper function? Something like this...
/**
* @param mixed ...$args
* @return string
*/
function hex(...$args) : string
{
$rgb = color(...$args)->getRgb();
return sprintf("#%02x%02x%02x", $rgb->getRed(), $rgb->getGreen(), $rgb->getBlue());
}
I would do a pull request but am pretty sure that there is a better way to do this with your setup. I have not had time to familiarize myself with how you setup the code.
I had considered this at one point but was undecided as to whether a hex helper would be best for converting hex strings to color objects or vice versa... Let me think on this a little more.
For now, color objects actually expose a toHexString method that should do the trick:
echo color("rebeccapurple")->toHexString(); // "#663399"
I should have mentioned that I tried that method. But with color that have an alpha channel, it does not return the correct hex value. It appends an 80 to the end. I did not look into why.
Oh I see... As of 72ebf7e5e49617fa7beb3332955a5d7082e7fbba this package supports rrggbbaa hex notation (caniuse, MDN), so that 80 on the end represents an alpha value of 0.5.
For better or worse, this was added primarily so that name('rgba(102, 51, 153, 0.5)') !== name('rgb(102, 51, 153)').
For the moment a (less than ideal) workaround would be to adjust the alpha value manually before calling toHexString():
$color = color('rgba(102, 51, 153, 0.5)');
$hexWithAlpha = $color->toHexString(); // "#66339980"
// ...
$hexWithoutAlpha = $color->with(['alpha' => 1.0])->toHexString(); // "#663399"
// OR
$hexWithoutAlpha = rgba($color, 1.0)->toHexString(); // "#663399"