You are here

function imageapi_hex2rgba in ImageAPI 5

Same name and namespace in other branches
  1. 6 imageapi.module \imageapi_hex2rgba()

Convert a hex string to its RGBA (Red, Green, Blue, Alpha) integer components.

Parameters

$hex: A string specifing an RGB color in the formats: '#ABC','ABC','#ABCD','ABCD','#AABBCC','AABBCC','#AABBCCDD','AABBCCDD'

Return value

An array with four elements for red, green, blue, and alpha.

1 call to imageapi_hex2rgba()
imagerotate in ./imagerotate.inc

File

./imageapi.module, line 421
An ImageAPI supporting mulitple image toolkits. Image toolkits are implemented as modules. Images are objects, but have no methods

Code

function imageapi_hex2rgba($hex) {
  $hex = ltrim($hex, '#');
  if (preg_match('/^[0-9a-f]{3}$/i', $hex)) {

    // 'FA3' is the same as 'FFAA33' so r=FF, g=AA, b=33
    $r = str_repeat($hex[0], 2);
    $g = str_repeat($hex[1], 2);
    $b = str_repeat($hex[2], 2);
    $a = '0';
  }
  elseif (preg_match('/^[0-9a-f]{6}$/i', $hex)) {

    // #FFAA33 or r=FF, g=AA, b=33
    list($r, $g, $b) = str_split($hex, 2);
    $a = '0';
  }
  elseif (preg_match('/^[0-9a-f]{8}$/i', $hex)) {

    // #FFAA33 or r=FF, g=AA, b=33
    list($r, $g, $b, $a) = str_split($hex, 2);
  }
  elseif (preg_match('/^[0-9a-f]{4}$/i', $hex)) {

    // 'FA37' is the same as 'FFAA3377' so r=FF, g=AA, b=33, a=77
    $r = str_repeat($hex[0], 2);
    $g = str_repeat($hex[1], 2);
    $b = str_repeat($hex[2], 2);
    $a = str_repeat($hex[3], 2);
  }
  else {

    //error: invalide hex string, TODO: set form error..
    return FALSE;
  }
  $r = hexdec($r);
  $g = hexdec($g);
  $b = hexdec($b);
  $a = hexdec($a);
  return array(
    $r,
    $g,
    $b,
    $a,
  );
}