当前位置:Gxlcms > PHP教程 > phpHexRGB颜色值互换的例子

phpHexRGB颜色值互换的例子

时间:2021-07-01 10:21:17 帮助过:7人阅读

  1. /**

  2. * Hex RGB颜色值互换
  3. * Edit bbs.it-home.org
  4. * at 2013/5/11
  5. */
  6. function HexToRGB($colour) {
  7. if ($colour [0] == '#') {
  8. $colour = substr ( $colour, 1 );
  9. }
  10. if (strlen ( $colour ) == 6) {
  11. list ( $r, $g, $b ) = array (
  12. $colour [0] . $colour [1],
  13. $colour [2] . $colour [3],
  14. $colour [4] . $colour [5]
  15. );
  16. } elseif (strlen ( $colour ) == 3) {
  17. list ( $r, $g, $b ) = array (
  18. $colour [0] . $colour [0],
  19. $colour [1] . $colour [1],
  20. $colour [2] . $colour [2]
  21. );
  22. } else {
  23. return false;
  24. }
  25. $r = hexdec ( $r );
  26. $g = hexdec ( $g );
  27. $b = hexdec ( $b );
  28. return array (
  29. 'red' => $r,
  30. 'green' => $g,
  31. 'blue' => $b
  32. );
  33. }
  34. function RGBToHex($rgb) {
  35. $regexp = "/^rgb\(([0-9]{0,3})\,\s*([0-9]{0,3})\,\s*([0-9]{0,3})\)/";
  36. $re = preg_match ( $regexp, $rgb, $match );
  37. $re = array_shift ( $match );
  38. $hexColor = "#";
  39. $hex = array (
  40. '0',
  41. '1',
  42. '2',
  43. '3',
  44. '4',
  45. '5',
  46. '6',
  47. '7',
  48. '8',
  49. '9',
  50. 'A',
  51. 'B',
  52. 'C',
  53. 'D',
  54. 'E',
  55. 'F'
  56. );
  57. for($i = 0; $i < 3; $i ++) {
  58. $r = null;
  59. $c = $match [$i];
  60. $hexAr = array ();

  61. while ( $c > 16 ) {

  62. $r = $c % 16;
  63. $c = ($c / 16) >> 0;
  64. array_push ( $hexAr, $hex [$r] );
  65. }
  66. array_push ( $hexAr, $hex [$c] );

  67. $ret = array_reverse ( $hexAr );

  68. $item = implode ( '', $ret );
  69. $item = str_pad ( $item, 2, '0', STR_PAD_LEFT );
  70. $hexColor .= $item;
  71. }
  72. return $hexColor;
  73. }

  74. //调用示例

  75. echo implode ( ",", HexToRGB ( "#F7F7DA" ) ) . "
    ";
  76. echo RGBToHex ( "rgb(247,247,218)" );
  77. ?>

人气教程排行