Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Image.php
Go to the documentation of this file.
1 <?php
7 
9 use Magento\Catalog\Model\View\Asset\ImageFactory;
10 use Magento\Catalog\Model\View\Asset\PlaceholderFactory;
16 
26 {
30  protected $_width;
31 
35  protected $_height;
36 
42  protected $_quality = 80;
43 
47  protected $_keepAspectRatio = true;
48 
52  protected $_keepFrame = true;
53 
57  protected $_keepTransparency = true;
58 
62  protected $_constrainOnly = true;
63 
67  protected $_backgroundColor = [255, 255, 255];
68 
72  protected $_baseFile;
73 
78 
82  protected $_newFile;
83 
87  protected $_processor;
88 
93 
97  protected $_angle;
98 
102  protected $_watermarkFile;
103 
108 
112  protected $_watermarkWidth;
113 
117  protected $_watermarkHeight;
118 
122  protected $_watermarkImageOpacity = 70;
123 
127  protected $_mediaDirectory;
128 
132  protected $_imageFactory;
133 
137  protected $_assetRepo;
138 
142  protected $_viewFileSystem;
143 
147  protected $_coreFileStorageDatabase = null;
148 
152  protected $_scopeConfig;
153 
158 
162  protected $_storeManager;
163 
167  private $viewAssetImageFactory;
168 
172  private $viewAssetPlaceholderFactory;
173 
177  private $imageAsset;
178 
182  private $paramsBuilder;
183 
187  private $cachePrefix = 'IMG_INFO';
188 
192  private $serializer;
193 
217  public function __construct(
218  \Magento\Framework\Model\Context $context,
219  \Magento\Framework\Registry $registry,
221  \Magento\Catalog\Model\Product\Media\Config $catalogProductMediaConfig,
222  \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase,
223  \Magento\Framework\Filesystem $filesystem,
224  \Magento\Framework\Image\Factory $imageFactory,
225  \Magento\Framework\View\Asset\Repository $assetRepo,
226  \Magento\Framework\View\FileSystem $viewFileSystem,
227  ImageFactory $viewAssetImageFactory,
228  PlaceholderFactory $viewAssetPlaceholderFactory,
229  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
230  \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
231  \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
232  array $data = [],
233  SerializerInterface $serializer = null,
234  ParamsBuilder $paramsBuilder = null
235  ) {
236  $this->_storeManager = $storeManager;
237  $this->_catalogProductMediaConfig = $catalogProductMediaConfig;
238  $this->_coreFileStorageDatabase = $coreFileStorageDatabase;
239  parent::__construct($context, $registry, $resource, $resourceCollection, $data);
240  $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
241  $this->_imageFactory = $imageFactory;
242  $this->_assetRepo = $assetRepo;
243  $this->_viewFileSystem = $viewFileSystem;
244  $this->_scopeConfig = $scopeConfig;
245  $this->viewAssetImageFactory = $viewAssetImageFactory;
246  $this->viewAssetPlaceholderFactory = $viewAssetPlaceholderFactory;
247  $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class);
248  $this->paramsBuilder = $paramsBuilder ?: ObjectManager::getInstance()->get(ParamsBuilder::class);
249  }
250 
255  public function setWidth($width)
256  {
257  $this->_width = $width;
258  return $this;
259  }
260 
264  public function getWidth()
265  {
266  return $this->_width;
267  }
268 
273  public function setHeight($height)
274  {
275  $this->_height = $height;
276  return $this;
277  }
278 
282  public function getHeight()
283  {
284  return $this->_height;
285  }
286 
293  public function setQuality($quality)
294  {
295  $this->_quality = $quality;
296  return $this;
297  }
298 
304  public function getQuality()
305  {
306  return $this->_quality;
307  }
308 
313  public function setKeepAspectRatio($keep)
314  {
315  $this->_keepAspectRatio = $keep && $keep !== 'false';
316  return $this;
317  }
318 
323  public function setKeepFrame($keep)
324  {
325  $this->_keepFrame = $keep && $keep !== 'false';
326  return $this;
327  }
328 
333  public function setKeepTransparency($keep)
334  {
335  $this->_keepTransparency = $keep && $keep !== 'false';
336  return $this;
337  }
338 
343  public function setConstrainOnly($flag)
344  {
345  $this->_constrainOnly = $flag && $flag !== 'false';
346  return $this;
347  }
348 
353  public function setBackgroundColor(array $rgbArray)
354  {
355  $this->_backgroundColor = $rgbArray;
356  return $this;
357  }
358 
363  public function setSize($size)
364  {
365  // determine width and height from string
366  list($width, $height) = explode('x', strtolower($size), 2);
367  foreach (['width', 'height'] as $wh) {
368  ${$wh}
369  = (int)${$wh};
370  if (empty(${$wh})) {
371  ${$wh}
372  = null;
373  }
374  }
375 
376  // set sizes
377  $this->setWidth($width)->setHeight($height);
378 
379  return $this;
380  }
381 
389  public function setBaseFile($file)
390  {
391  $this->_isBaseFilePlaceholder = false;
392 
393  $this->imageAsset = $this->viewAssetImageFactory->create(
394  [
395  'miscParams' => $this->getMiscParams(),
396  'filePath' => $file,
397  ]
398  );
399  if ($file == 'no_selection' || !$this->_fileExists($this->imageAsset->getSourceFile())) {
400  $this->_isBaseFilePlaceholder = true;
401  $this->imageAsset = $this->viewAssetPlaceholderFactory->create(
402  [
403  'type' => $this->getDestinationSubdir(),
404  ]
405  );
406  }
407 
408  $this->_baseFile = $this->imageAsset->getSourceFile();
409 
410  return $this;
411  }
412 
416  public function getBaseFile()
417  {
418  return $this->_baseFile;
419  }
420 
425  public function getNewFile()
426  {
427  return $this->_newFile;
428  }
429 
435  public function isBaseFilePlaceholder()
436  {
437  return (bool)$this->_isBaseFilePlaceholder;
438  }
439 
444  public function setImageProcessor($processor)
445  {
446  $this->_processor = $processor;
447  return $this;
448  }
449 
453  public function getImageProcessor()
454  {
455  if (!$this->_processor) {
456  $filename = $this->getBaseFile() ? $this->_mediaDirectory->getAbsolutePath($this->getBaseFile()) : null;
457  $this->_processor = $this->_imageFactory->create($filename);
458  }
459  $this->_processor->keepAspectRatio($this->_keepAspectRatio);
460  $this->_processor->keepFrame($this->_keepFrame);
461  $this->_processor->keepTransparency($this->_keepTransparency);
462  $this->_processor->constrainOnly($this->_constrainOnly);
463  $this->_processor->backgroundColor($this->_backgroundColor);
464  $this->_processor->quality($this->_quality);
465  return $this->_processor;
466  }
467 
472  public function resize()
473  {
474  if ($this->getWidth() === null && $this->getHeight() === null) {
475  return $this;
476  }
477  $this->getImageProcessor()->resize($this->_width, $this->_height);
478  return $this;
479  }
480 
485  public function rotate($angle)
486  {
487  $angle = (int) $angle;
488  $this->getImageProcessor()->rotate($angle);
489  return $this;
490  }
491 
500  public function setAngle($angle)
501  {
502  $this->_angle = $angle;
503  return $this;
504  }
505 
519  public function setWatermark(
520  $file,
521  $position = null,
522  $size = null,
523  $width = null,
524  $height = null,
525  $opacity = null
526  ) {
527  if ($this->_isBaseFilePlaceholder) {
528  return $this;
529  }
530 
531  if ($file) {
532  $this->setWatermarkFile($file);
533  } else {
534  return $this;
535  }
536 
537  if ($position) {
538  $this->setWatermarkPosition($position);
539  }
540  if ($size) {
541  $this->setWatermarkSize($size);
542  }
543  if ($width) {
544  $this->setWatermarkWidth($width);
545  }
546  if ($height) {
547  $this->setWatermarkHeight($height);
548  }
549  if ($opacity) {
550  $this->setWatermarkImageOpacity($opacity);
551  }
552  $filePath = $this->_getWatermarkFilePath();
553 
554  if ($filePath) {
555  $imagePreprocessor = $this->getImageProcessor();
556  $imagePreprocessor->setWatermarkPosition($this->getWatermarkPosition());
557  $imagePreprocessor->setWatermarkImageOpacity($this->getWatermarkImageOpacity());
558  $imagePreprocessor->setWatermarkWidth($this->getWatermarkWidth());
559  $imagePreprocessor->setWatermarkHeight($this->getWatermarkHeight());
560  $imagePreprocessor->watermark($filePath);
561  }
562 
563  return $this;
564  }
565 
569  public function saveFile()
570  {
571  if ($this->_isBaseFilePlaceholder) {
572  return $this;
573  }
574  $filename = $this->getBaseFile() ? $this->imageAsset->getPath() : null;
575  $this->getImageProcessor()->save($filename);
576  $this->_coreFileStorageDatabase->saveFile($filename);
577  return $this;
578  }
579 
583  public function getUrl()
584  {
585  return $this->imageAsset->getUrl();
586  }
587 
592  public function setDestinationSubdir($dir)
593  {
594  $this->_destinationSubdir = $dir;
595  return $this;
596  }
597 
601  public function getDestinationSubdir()
602  {
604  }
605 
609  public function isCached()
610  {
611  $path = $this->imageAsset->getPath();
612  return is_array($this->loadImageInfoFromCache($path)) || file_exists($path);
613  }
614 
621  public function setWatermarkFile($file)
622  {
623  $this->_watermarkFile = $file;
624  return $this;
625  }
626 
632  public function getWatermarkFile()
633  {
634  return $this->_watermarkFile;
635  }
636 
643  protected function _getWatermarkFilePath()
644  {
645  $filePath = false;
646 
647  if (!($file = $this->getWatermarkFile())) {
648  return $filePath;
649  }
650  $baseDir = $this->_catalogProductMediaConfig->getBaseMediaPath();
651 
652  $candidates = [
653  $baseDir . '/watermark/stores/' . $this->_storeManager->getStore()->getId() . $file,
654  $baseDir . '/watermark/websites/' . $this->_storeManager->getWebsite()->getId() . $file,
655  $baseDir . '/watermark/default/' . $file,
656  $baseDir . '/watermark/' . $file,
657  ];
658  foreach ($candidates as $candidate) {
659  if ($this->_mediaDirectory->isExist($candidate)) {
660  $filePath = $this->_mediaDirectory->getAbsolutePath($candidate);
661  break;
662  }
663  }
664  if (!$filePath) {
665  $filePath = $this->_viewFileSystem->getStaticFileName($file);
666  }
667 
668  return $filePath;
669  }
670 
677  public function setWatermarkPosition($position)
678  {
679  $this->_watermarkPosition = $position;
680  return $this;
681  }
682 
688  public function getWatermarkPosition()
689  {
691  }
692 
699  public function setWatermarkImageOpacity($imageOpacity)
700  {
701  $this->_watermarkImageOpacity = $imageOpacity;
702  return $this;
703  }
704 
710  public function getWatermarkImageOpacity()
711  {
713  }
714 
721  public function setWatermarkSize($size)
722  {
723  if (is_array($size)) {
724  $this->setWatermarkWidth($size['width'])->setWatermarkHeight($size['height']);
725  }
726  return $this;
727  }
728 
735  public function setWatermarkWidth($width)
736  {
737  $this->_watermarkWidth = $width;
738  return $this;
739  }
740 
746  public function getWatermarkWidth()
747  {
748  return $this->_watermarkWidth;
749  }
750 
757  public function setWatermarkHeight($height)
758  {
759  $this->_watermarkHeight = $height;
760  return $this;
761  }
762 
768  public function getWatermarkHeight()
769  {
771  }
772 
776  public function clearCache()
777  {
778  $directory = $this->_catalogProductMediaConfig->getBaseMediaPath() . '/cache';
779  $this->_mediaDirectory->delete($directory);
780 
781  $this->_coreFileStorageDatabase->deleteFolder($this->_mediaDirectory->getAbsolutePath($directory));
782  $this->clearImageInfoFromCache();
783  }
784 
792  protected function _fileExists($filename)
793  {
794  if ($this->_mediaDirectory->isFile($filename)) {
795  return true;
796  } else {
797  return $this->_coreFileStorageDatabase->saveFileToFilesystem(
798  $this->_mediaDirectory->getAbsolutePath($filename)
799  );
800  }
801  }
802 
808  public function getResizedImageInfo()
809  {
810  try {
811  if ($this->isBaseFilePlaceholder() == true) {
812  $image = $this->imageAsset->getSourceFile();
813  } else {
814  $image = $this->imageAsset->getPath();
815  }
816 
817  $imageProperties = $this->getImageSize($image);
818 
819  return $imageProperties;
820  } finally {
821  if (empty($imageProperties)) {
822  throw new NotLoadInfoImageException(__('Can\'t get information about the picture: %1', $image));
823  }
824  }
825  }
826 
833  private function getMiscParams()
834  {
835  return $this->paramsBuilder->build(
836  [
837  'type' => $this->getDestinationSubdir(),
838  'width' => $this->getWidth(),
839  'height' => $this->getHeight(),
840  'frame' => $this->_keepFrame,
841  'constrain' => $this->_constrainOnly,
842  'aspect_ratio' => $this->_keepAspectRatio,
843  'transparency' => $this->_keepTransparency,
844  'background' => $this->_backgroundColor,
845  'angle' => $this->_angle,
846  'quality' => $this->_quality
847  ]
848  );
849  }
850 
857  private function getImageSize($imagePath)
858  {
859  $imageInfo = $this->loadImageInfoFromCache($imagePath);
860  if (!isset($imageInfo['size'])) {
861  $imageSize = getimagesize($imagePath);
862  $this->saveImageInfoToCache(['size' => $imageSize], $imagePath);
863  return $imageSize;
864  } else {
865  return $imageInfo['size'];
866  }
867  }
868 
876  private function saveImageInfoToCache(array $imageInfo, string $imagePath)
877  {
878  $imagePath = $this->cachePrefix . $imagePath;
879  $this->_cacheManager->save(
880  $this->serializer->serialize($imageInfo),
881  $imagePath,
882  [$this->cachePrefix]
883  );
884  }
885 
892  private function loadImageInfoFromCache(string $imagePath)
893  {
894  $imagePath = $this->cachePrefix . $imagePath;
895  $cacheData = $this->_cacheManager->load($imagePath);
896  if (!$cacheData) {
897  return false;
898  } else {
899  return $this->serializer->unserialize($cacheData);
900  }
901  }
902 
908  private function clearImageInfoFromCache()
909  {
910  $this->_cacheManager->clean([$this->cachePrefix]);
911  }
912 }
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Catalog\Model\Product\Media\Config $catalogProductMediaConfig, \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase, \Magento\Framework\Filesystem $filesystem, \Magento\Framework\Image\Factory $imageFactory, \Magento\Framework\View\Asset\Repository $assetRepo, \Magento\Framework\View\FileSystem $viewFileSystem, ImageFactory $viewAssetImageFactory, PlaceholderFactory $viewAssetPlaceholderFactory, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[], SerializerInterface $serializer=null, ParamsBuilder $paramsBuilder=null)
Definition: Image.php:217
setBackgroundColor(array $rgbArray)
Definition: Image.php:353
$baseDir
Definition: autoload.php:9
$processor
Definition: 404.php:10
$storeManager
__()
Definition: __.php:13
$resource
Definition: bulk.php:12
$filesystem
setWatermarkImageOpacity($imageOpacity)
Definition: Image.php:699
setWatermark( $file, $position=null, $size=null, $width=null, $height=null, $opacity=null)
Definition: Image.php:519