Image.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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
  54. * @return void
  55. */
  56. public function rotate($angle)
  57. {
  58. $resource = imagerotate($this->_resource, $angle, 0);
  59. imagedestroy($this->_resource);
  60. $this->_resource = $resource;
  61. }
  62. /**
  63. * @return void
  64. */
  65. public function rotateLeft()
  66. {
  67. $this->rotate(90);
  68. }
  69. /**
  70. * @return void
  71. */
  72. public function rotateRight()
  73. {
  74. $this->rotate(270);
  75. }
  76. /**
  77. * @param string $path
  78. * @return void
  79. */
  80. public function saveJpeg($path)
  81. {
  82. imagejpeg($this->_resource, $path);
  83. }
  84. }