Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ImagesGenerator.php
Go to the documentation of this file.
1 <?php
7 
9 
14 {
18  private $filesystem;
19 
23  private $mediaConfig;
24 
29  public function __construct(
30  \Magento\Framework\Filesystem $filesystem,
31  \Magento\Catalog\Model\Product\Media\Config $mediaConfig
32  ) {
33  $this->filesystem = $filesystem;
34  $this->mediaConfig = $mediaConfig;
35  }
36 
43  public function generate($config)
44  {
45  $binaryData = '';
46  $data = str_split(sha1($config['image-name']), 2);
47  foreach ($data as $item) {
48  $binaryData .= base_convert($item, 16, 2);
49  }
50  $binaryData = str_split($binaryData, 1);
51 
52  $image = imagecreate($config['image-width'], $config['image-height']);
53  $bgColor = imagecolorallocate($image, 240, 240, 240);
54  $fgColor = imagecolorallocate($image, mt_rand(0, 230), mt_rand(0, 230), mt_rand(0, 230));
55  $colors = [$fgColor, $bgColor];
56  imagefilledrectangle($image, 0, 0, $config['image-width'], $config['image-height'], $bgColor);
57 
58  for ($row = 10; $row < ($config['image-height'] - 10); $row += 10) {
59  for ($col = 10; $col < ($config['image-width'] - 10); $col += 10) {
60  if (next($binaryData) === false) {
61  reset($binaryData);
62  }
63 
64  imagefilledrectangle($image, $row, $col, $row + 10, $col + 10, $colors[current($binaryData)]);
65  }
66  }
67 
68  $mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
69  $relativePathToMedia = $mediaDirectory->getRelativePath($this->mediaConfig->getBaseTmpMediaPath());
70  $mediaDirectory->create($relativePathToMedia);
71 
72  $absolutePathToMedia = $mediaDirectory->getAbsolutePath($this->mediaConfig->getBaseTmpMediaPath());
73  $imagePath = $absolutePathToMedia . DIRECTORY_SEPARATOR . $config['image-name'];
74  imagejpeg($image, $imagePath, 100);
75 
76  return $imagePath;
77  }
78 }
$config
Definition: fraud_order.php:17
__construct(\Magento\Framework\Filesystem $filesystem, \Magento\Catalog\Model\Product\Media\Config $mediaConfig)
$mediaDirectory
$filesystem
$mediaConfig