Image.php 1.8 KB

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