Convert rgb to hex in php

in my code i have

$color = rgb[255, 255, 255];

i want to convert this into hex color code.Out put like

$color = '#ffffff';

asked Oct 6, 2015 at 5:51

2

A simple sprintf will do.

$color = sprintf["#%02x%02x%02x", 13, 0, 255]; // #0d00ff

To break down the format:

  • # - the literal character #
  • % - start of conversion specification
  • 0 - character to be used for padding
  • 2 - minimum number of characters the conversion should result in, padded with the above as necessary
  • x - the argument is treated as an integer and presented as a hexadecimal number with lowercase letters
  • %02x%02x - the above four repeated twice more

answered Oct 6, 2015 at 19:06

user3942918user3942918

25.2k12 gold badges54 silver badges67 bronze badges

0

You can use following function

function fromRGB[$R, $G, $B]
{

    $R = dechex[$R];
    if [strlen[$R]blue[]; // 255

echo $rgb; // rgb[55,155,255]

$rgba = $rgb->toRgba[]; // `Spatie\Color\Rgba`
$rgba->alpha[]; // 1
echo $rgba; // rgba[55,155,255,1]

$hex = $rgb->toHex[]; // `Spatie\Color\Hex`
echo $hex; // #379bff

$hsl = $rgb->toHsl[];
echo $hsl; // hsl[210,100%,100%]

answered Feb 22, 2021 at 15:41

Ostap BrehinOstap Brehin

2,4893 gold badges23 silver badges26 bronze badges

Chủ Đề