1
0

Image.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace fphammerle\helpers;
  3. class Image
  4. {
  5. use \fphammerle\helpers\PropertyAccessTrait;
  6. protected $_resource = null;
  7. private function __construct()
  8. {
  9. }
  10. public function __destruct()
  11. {
  12. if($this->_resource) {
  13. imagedestroy($this->_resource);
  14. }
  15. }
  16. /**
  17. * @param string $path
  18. * @return Image
  19. */
  20. public static function fromFile($path)
  21. {
  22. $image = new self;
  23. switch(exif_imagetype($path)) {
  24. case IMAGETYPE_JPEG:
  25. $image->_resource = imagecreatefromjpeg($path);
  26. break;
  27. case IMAGETYPE_PNG:
  28. $image->_resource = imagecreatefrompng($path);
  29. break;
  30. default:
  31. throw new \InvalidArgumentException("type of '$path' is not supported");
  32. }
  33. return $image;
  34. }
  35. public function getWidth()
  36. {
  37. return imagesx($this->_resource);
  38. }
  39. public function getColorAt($x, $y)
  40. {
  41. $colors = imagecolorsforindex(
  42. $this->_resource,
  43. imagecolorat($this->_resource, $x, $y)
  44. );
  45. return new \fphammerle\helpers\colors\RGBA(
  46. $colors['red'] / 0xFF,
  47. $colors['green'] / 0xFF,
  48. $colors['blue'] / 0xFF,
  49. 1 - $colors['alpha'] / 127
  50. );
  51. }
  52. /**
  53. * @param float $angle anticlockwise
  54. * @return void
  55. */
  56. public function rotate($angle)
  57. {
  58. $angle = fmod($angle, 360);
  59. if(abs($angle) > 1e-10) {
  60. $resource = imagerotate($this->_resource, $angle, 0);
  61. imagedestroy($this->_resource);
  62. $this->_resource = $resource;
  63. }
  64. }
  65. /**
  66. * @return void
  67. */
  68. public function rotateLeft()
  69. {
  70. $this->rotate(90);
  71. }
  72. /**
  73. * @return void
  74. */
  75. public function rotateRight()
  76. {
  77. $this->rotate(270);
  78. }
  79. /**
  80. * @param string $path
  81. * @return void
  82. */
  83. public function saveJpeg($path)
  84. {
  85. imagejpeg($this->_resource, $path);
  86. }
  87. }