Image.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace Tool\MayouTool\Captcha\Src;
  3. class Image
  4. {
  5. /**
  6. * 已生成的图片
  7. *
  8. * @var resource
  9. */
  10. protected $image;
  11. public function __construct($image)
  12. {
  13. $this->image = $image;
  14. }
  15. /**
  16. * 获取 base64的数据,用做image标签的src
  17. *
  18. * @return string
  19. */
  20. public function getDataUrl()
  21. {
  22. return 'data:image/jpeg;base64,' . $this->getBase64();
  23. }
  24. /**
  25. * 获取base64
  26. *
  27. * @return string
  28. */
  29. public function getBase64()
  30. {
  31. return base64_encode($this->getContent());
  32. }
  33. /**
  34. * 获取图片
  35. *
  36. * @return resource
  37. */
  38. public function getImage()
  39. {
  40. return $this->image;
  41. }
  42. /**
  43. * 获取图片
  44. *
  45. * @return resource
  46. */
  47. public function getContext()
  48. {
  49. return $this->getImage();
  50. }
  51. /**
  52. * 保存为图片
  53. *
  54. * @param string $filename 文件名
  55. * @return $this
  56. */
  57. public function save($filename)
  58. {
  59. $this->output($filename);
  60. return $this;
  61. }
  62. /**
  63. * 直接输出
  64. *
  65. * @param string|null $filename 文件名
  66. * @return $this
  67. */
  68. public function output($filename = null)
  69. {
  70. imagejpeg($this->getContext(), $filename);
  71. return $this;
  72. }
  73. /**
  74. * 获取输出内容
  75. *
  76. * @return string
  77. */
  78. public function getContent()
  79. {
  80. ob_start();
  81. $this->output();
  82. return ob_get_clean();
  83. }
  84. }