Skip to content

Instantly share code, notes, and snippets.

@alexmustin
Created April 25, 2019 23:42
Show Gist options
  • Select an option

  • Save alexmustin/82b084d22ff52e9f043df295baa38cef to your computer and use it in GitHub Desktop.

Select an option

Save alexmustin/82b084d22ff52e9f043df295baa38cef to your computer and use it in GitHub Desktop.

Revisions

  1. alexmustin revised this gist Apr 25, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion functions.php
    Original file line number Diff line number Diff line change
    @@ -37,7 +37,7 @@ function hex2rgba( $color, $opacity = false ) {
    $output = 'rgb(' . implode( ",", $rgb ) . ')';
    }

    //Return rgb(a) color string
    // Return rgb(a) color string
    return $output;

    }
  2. alexmustin created this gist Apr 25, 2019.
    50 changes: 50 additions & 0 deletions functions.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    <?php

    //* Function to convert Hex colors to RGBA
    function hex2rgba( $color, $opacity = false ) {

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

    // Return default color if no color provided
    if ( empty( $color ) ) {
    return $defaultColor;
    }

    // Ignore "#" if provided
    if ( $color[0] == '#' ) {
    $color = substr( $color, 1 );
    }

    // Check if color has 6 or 3 characters, 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 hex values to rgb values
    $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;

    }

    /*
    * Example Usage:
    * $mycolor = '#ff0000';
    * $rgb = hex2rgba($mycolor);
    * $rgba = hex2rgba($mycolor, 0.5);
    */