Skip to content

Colors

These functions are for working with color values.

adjustBrightness

This function adjusts the input color by ± 255 steps.

<?php 

function adjustBrightness( $hex, $steps ) { //--------------------------------------------------------------------
    // Steps should be between -255 and 255. Negative = darker, positive = lighter
    if ( $steps == "" ) { $steps = 0; }

    $steps = max( -255, min( 255, $steps ) );

    // Normalize into a six character long hex string
    //$hex = str_replace('#', '', $hex);
    if ( strlen( $hex ) == 3 ) {
        $hex = str_repeat( substr( $hex, 0, 1 ), 2 ) . str_repeat( substr( $hex, 1, 1 ), 2 ) . str_repeat( substr( $hex, 2, 1 ), 2 );
    }

    // Split into three parts: R, G and B
    $color_parts = str_split( $hex, 2 );
    //$return = '#';

    foreach ( $color_parts as $color ) {
        $color = hexdec( $color ); // Convert to decimal
        $color = max( 0, min( 255, $color + $steps ) ); // Adjust color
        $return .= str_pad( dechex( $color ), 2, '0', STR_PAD_LEFT ); // Make two char hex code
    }

    return $return;
} //end function adjustBrightness

?>

calcColorLuma

This function calculate the approximate Luma of a color based on one of the simpler algorithms.

<?php

function calcColorLuma( $hex ) { //--------------------------------------------------------------------
    // Split into three parts: R, G and B
    $color_parts = str_split( $hex, 2 );

    foreach ( $color_parts as $color ) {
        $arrColors[] = hexdec( $color );
    }

    // Calculate the Luma
    $intLuma = ( ( $arrColors[ 0 ] * 2 ) + ( $arrColors[ 1 ] * 3 ) + ( $arrColors[ 2 ] * 1 ) ) / 6;

    return $intLuma;
} //end function calcColorLuma

?>

invertColor

This function inverts a color.

<?php

function invertColor( $color ) { //--------------------------------------------------------------------

    if ( strlen( $color ) != 6 ) {
        return '000000';
    }
    $rgb = '';
    for ( $x = 0; $x < 3; $x++ ) {
        $c = 255 - hexdec( substr( $color, ( 2 * $x ), 2 ) );
        $c = ( $c < 0 ) ? 0 : dechex( $c );
        $rgb .= ( strlen( $c ) < 2 ) ? '0' . $c : $c;
    }

    return $rgb;

} //end function invertColor

?>
Back to top