Identicon.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace Identicon;
  3. use Identicon\Generator\GdGenerator;
  4. use Identicon\Generator\GeneratorInterface;
  5. /**
  6. * @author Benjamin Laugueux <benjamin@yzalis.com>
  7. */
  8. class Identicon
  9. {
  10. /**
  11. * @var GeneratorInterface
  12. */
  13. private $generator;
  14. public function __construct($generator = null)
  15. {
  16. if (null === $generator) {
  17. $this->generator = new GdGenerator();
  18. } else {
  19. $this->generator = $generator;
  20. }
  21. }
  22. /**
  23. * Set the image generetor
  24. *
  25. * @param GeneratorInterface $generator
  26. *
  27. * @throws \Exception
  28. */
  29. public function setGenerator(GeneratorInterface $generator)
  30. {
  31. $this->generator = $generator;
  32. return $this;
  33. }
  34. /**
  35. * Display an Identicon image
  36. *
  37. * @param string $string
  38. * @param integer $size
  39. * @param string $color
  40. * @param string $backgroundColor
  41. */
  42. public function displayImage($string, $size = 64, $color = null, $backgroundColor = null)
  43. {
  44. header("Content-Type: image/png");
  45. echo $this->getImageData($string, $size, $color, $backgroundColor);
  46. }
  47. /**
  48. * Get an Identicon PNG image data
  49. *
  50. * @param string $string
  51. * @param integer $size
  52. * @param string $color
  53. * @param string $backgroundColor
  54. *
  55. * @return string
  56. */
  57. public function getImageData($string, $size = 64, $color = null, $backgroundColor = null)
  58. {
  59. return $this->generator->getImageBinaryData($string, $size, $color, $backgroundColor);
  60. }
  61. /**
  62. * Get an Identicon PNG image resource
  63. *
  64. * @param string $string
  65. * @param integer $size
  66. * @param string $color
  67. * @param string $backgroundColor
  68. *
  69. * @return string
  70. */
  71. public function getImageResource($string, $size = 64, $color = null, $backgroundColor = null)
  72. {
  73. return $this->generator->getImageResource($string, $size, $color, $backgroundColor);
  74. }
  75. /**
  76. * Get an Identicon PNG image data as base 64 encoded
  77. *
  78. * @param string $string
  79. * @param integer $size
  80. * @param string $color
  81. * @param string $backgroundColor
  82. *
  83. * @return string
  84. */
  85. public function getImageDataUri($string, $size = 64, $color = null, $backgroundColor = null)
  86. {
  87. return sprintf('data:image/png;base64,%s', base64_encode($this->getImageData($string, $size, $color, $backgroundColor)));
  88. }
  89. }