PHP: Convert Hex Color to RGB and RGB to Hex

by Websitedays · 2009-04-10 · Thread #30
WebsitedaysMember

PHP: Convert Hex Color to RGB and RGB to Hex

Here are two handy PHP functions for color conversion:

<?php
function hexToRgb($hex) {
  $hex = ltrim($hex, "#");
  if (strlen($hex) == 3) {
    $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
  }
  return array(
    "r" => hexdec(substr($hex, 0, 2)),
    "g" => hexdec(substr($hex, 2, 2)),
    "b" => hexdec(substr($hex, 4, 2))
  );
}
function rgbToHex($r, $g, $b) {
  return sprintf("#%02x%02x%02x", $r, $g, $b);
}
?>
by TomDundore · 2009-04-11
TomDundoreMember

Great snippet! Here's a CSS-ready string version:

function hexToRgbCss($hex) {
  $rgb = hexToRgb($hex);
  return "rgb(".$rgb["r"].",".$rgb["g"].",".$rgb["b"].")";
}
by Websitedays · 2009-04-12
WebsitedaysMember

Good addition! See also the full thread archive: earlier version · this thread (no-www)

← Back to Forum Index