欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php Hex RGB颜色值互换的例子

程序员文章站 2022-03-27 23:51:20
...
  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 $r = null;
  58. $c = $match [$i];
  59. $hexAr = array ();
  60. while ( $c > 16 ) {

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

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

  74. echo implode ( ",", HexToRGB ( "#F7F7DA" ) ) . "
    ";
  75. echo RGBToHex ( "rgb(247,247,218)" );
  76. ?>
复制代码