imagick.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Grav\Plugin;
  3. require_once 'interface.php';
  4. /**
  5. * Class ImagickAdapter
  6. * @package Grav\Plugin
  7. */
  8. class ImagickAdapter implements ResizeAdapterInterface
  9. {
  10. private $image;
  11. private $format;
  12. /**
  13. * Initiates a new ImagickAdapter instance
  14. * @param string $source - Source image path
  15. */
  16. public function __construct($source)
  17. {
  18. $this->image = new \Imagick($source);
  19. $this->format = strtolower($this->image->getImageFormat());
  20. return $this;
  21. }
  22. /**
  23. * Gets the image format
  24. * @return string - Either 'JPEG' or 'PNG'
  25. */
  26. public function getFormat()
  27. {
  28. return $this->format;
  29. }
  30. /**
  31. * Resizes the image to the specified dimensions
  32. * @param float $width
  33. * @param float $height
  34. * @return ImagickAdapter - Returns $this
  35. */
  36. public function resize($width, $height)
  37. {
  38. $this->image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1);
  39. return $this;
  40. }
  41. /**
  42. * Sets JPEG quality of target image
  43. * @param int $quality
  44. * @return ImagickAdapter - Returns $this
  45. */
  46. public function setQuality($quality)
  47. {
  48. $this->image->setImageCompressionQuality($quality);
  49. return $this;
  50. }
  51. /**
  52. * Generates image and saves it to disk
  53. * @param string $filename - Target filename for image
  54. * @return bool - Returns true if successful, false otherwise
  55. */
  56. public function save($filename)
  57. {
  58. $format = $this->getFormat();
  59. if ($format == 'jpeg') {
  60. $this->image->setImageCompression(\Imagick::COMPRESSION_JPEG);
  61. } else if ($format == 'png') {
  62. $this->image->setImageCompression(\Imagick::COMPRESSION_ZIP);
  63. }
  64. $result = $this->image->writeImage($filename);
  65. $this->image->clear();
  66. return (bool) $result;
  67. }
  68. }