Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RGB to hex color values in PHP

Tags:

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';
like image 949
ravichandra Avatar asked Oct 06 '15 05:10

ravichandra


People also ask

How do I find the hex code for a color on a website Mac?

If you're looking for HEX codes for web work e.g. #e5e5e5 , it can be found under View -> Display Values in the Digital Color Meter.


4 Answers

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
like image 121
user3942918 Avatar answered Sep 25 '22 16:09

user3942918


You can use following function

function fromRGB($R, $G, $B)
{

    $R = dechex($R);
    if (strlen($R)<2)
    $R = '0'.$R;

    $G = dechex($G);
    if (strlen($G)<2)
    $G = '0'.$G;

    $B = dechex($B);
    if (strlen($B)<2)
    $B = '0'.$B;

    return '#' . $R . $G . $B;
}

Then, echo fromRGB(115,25,190); will print #7319be

Source: RGB to hex colors and hex colors to RGB - PHP

like image 36
Suyog Avatar answered Sep 24 '22 16:09

Suyog


You can try this simple piece of code below. You can pass the rgb code dynamically as well in the code.

$rgb = (123,222,132);
$rgbarr = explode(",",$rgb,3);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);

This will code return like #7bde84

like image 25
IAmMilinPatel Avatar answered Sep 26 '22 16:09

IAmMilinPatel


Here is a function that will accept the string version of either an rgb or rgba and return the hex color.

    function rgb_to_hex( string $rgba ) : string {
        if ( strpos( $rgba, '#' ) === 0 ) {
            return $rgba;
        }

        preg_match( '/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i', $rgba, $by_color );

        return sprintf( '#%02x%02x%02x', $by_color[1], $by_color[2], $by_color[3] );
    }

Example: rgb_to_hex( 'rgba(203, 86, 153, 0.8)' ); // Returns #cb5699

like image 32
Mat Lipe Avatar answered Sep 23 '22 16:09

Mat Lipe