Hướng dẫn php hex to rgb

As far as we know, many of WordPress theme developers use a lot of design options inside their themes, just as we do. Which means that you usually provide color pickers so the users may easily change color settings for their websites.

This usually means that you will need to create dynamic CSS files instead of a hard-coded CSS, so the user’s color changes may apply on the website instantly. As for HTML5/CSS3 standards, hex colors can’t always do all the work so you need to work with RGB or RGBA color codes.

While we have been struggling with this sometimes, we have made a little PHP helper function which converts hex color code string into RGB or even RGBA color. For example, if you want to add opacity to the color of some element  and basically achieve “transparent hex code”.

Top Hosting recommended by Meks

Convert hex color to rgba – PHP function

Here’s the code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

/* Convert hexdec color string to rgb(a) string */

functionhex2rgba($color,$opacity=false){

$default='rgb(0,0,0)';

//Return default if no color provided

if(empty($color))

          return$default;

//Sanitize $color if "#" is provided

        if ($color[0]=='#'){

         $color=substr($color,1);

        }

        //Check if color has 6 or 3 characters and get values

        if(strlen($color)==6){

                $hex=array($color[0].$color[1], $color[2].$color[3],$color[4].$color[5]);

        } elseif(strlen($color)==3){

                $hex= array($color[0].$color[0],$color[1].$color[1], $color[2].$color[2]);

        }else{

                return $default;

        }

        //Convert hexadec to rgb

        $rgb=  array_map('hexdec', $hex);

        //Check if opacity is set(rgba or rgb)

        if($opacity){

         if(abs($opacity)>1)

         $opacity=1.0;

         $output ='rgba('.implode(",",$rgb).','.$opacity.')';

        }else{

         $output='rgb('.implode(",",$rgb).')';

        }

        //Return rgb(a) color string

        return $output;

}

So far so good! Now we are going to show you how this function can be helpful whilst creating dynamic CSS with a simple example below.

Usage example:

/* Here's a usage example how to use this function for dynamicaly created CSS */

$color='#ffa226';

$rgb=hex2rgba($color);

$rgba= hex2rgba($color,0.7);

/* CSS output */

echo'

div.example{

background: '.$rgb.';

color: '.$rgba.';

}

';