ImageColor.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Gregwar\Image;
  3. /**
  4. * Color manipulation class.
  5. */
  6. class ImageColor
  7. {
  8. private static $colors = array(
  9. 'black' => 0x000000,
  10. 'silver' => 0xc0c0c0,
  11. 'gray' => 0x808080,
  12. 'teal' => 0x008080,
  13. 'aqua' => 0x00ffff,
  14. 'blue' => 0x0000ff,
  15. 'navy' => 0x000080,
  16. 'green' => 0x008000,
  17. 'lime' => 0x00ff00,
  18. 'white' => 0xffffff,
  19. 'fuschia' => 0xff00ff,
  20. 'purple' => 0x800080,
  21. 'olive' => 0x808000,
  22. 'yellow' => 0xffff00,
  23. 'orange' => 0xffA500,
  24. 'red' => 0xff0000,
  25. 'maroon' => 0x800000,
  26. 'transparent' => 0x7fffffff,
  27. );
  28. public static function gdAllocate($image, $color)
  29. {
  30. $colorRGBA = self::parse($color);
  31. $b = ($colorRGBA) & 0xff;
  32. $colorRGBA >>= 8;
  33. $g = ($colorRGBA) & 0xff;
  34. $colorRGBA >>= 8;
  35. $r = ($colorRGBA) & 0xff;
  36. $colorRGBA >>= 8;
  37. $a = ($colorRGBA) & 0xff;
  38. $c = imagecolorallocatealpha($image, $r, $g, $b, $a);
  39. if ($color == 'transparent') {
  40. imagecolortransparent($image, $c);
  41. }
  42. return $c;
  43. }
  44. public static function parse($color)
  45. {
  46. // Direct color representation (ex: 0xff0000)
  47. if (!is_string($color) && is_numeric($color)) {
  48. return $color;
  49. }
  50. // Color name (ex: "red")
  51. if (isset(self::$colors[$color])) {
  52. return self::$colors[$color];
  53. }
  54. if (is_string($color)) {
  55. $color_string = str_replace(' ', '', $color);
  56. // Color string (ex: "ff0000", "#ff0000" or "0xfff")
  57. if (preg_match('/^(#|0x|)([0-9a-f]{3,6})/i', $color_string, $matches)) {
  58. $col = $matches[2];
  59. if (strlen($col) == 6) {
  60. return hexdec($col);
  61. }
  62. if (strlen($col) == 3) {
  63. $r = '';
  64. for ($i = 0; $i < 3; ++$i) {
  65. $r .= $col[$i].$col[$i];
  66. }
  67. return hexdec($r);
  68. }
  69. }
  70. // Colors like "rgb(255, 0, 0)"
  71. if (preg_match('/^rgb\(([0-9]+),([0-9]+),([0-9]+)\)/i', $color_string, $matches)) {
  72. $r = $matches[1];
  73. $g = $matches[2];
  74. $b = $matches[3];
  75. if ($r >= 0 && $r <= 0xff && $g >= 0 && $g <= 0xff && $b >= 0 && $b <= 0xff) {
  76. return ($r << 16) | ($g << 8) | ($b);
  77. }
  78. }
  79. }
  80. throw new \InvalidArgumentException('Invalid color: '.$color);
  81. }
  82. }