Skip to content

Commit ba16cb2

Browse files
Chhandak.BaruaChhandak.Barua
authored andcommitted
ACP2E-3504: Product images not resized when added as configurable product
1 parent 2f2e1a2 commit ba16cb2

File tree

5 files changed

+108
-71
lines changed

5 files changed

+108
-71
lines changed

app/code/Magento/Catalog/Controller/Adminhtml/Product/Gallery/Upload.php

Lines changed: 1 addition & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,9 @@
99
use Magento\Framework\App\Filesystem\DirectoryList;
1010
use Magento\Framework\App\ObjectManager;
1111
use Magento\Framework\Exception\LocalizedException;
12-
use Magento\Backend\Model\Image\UploadResizeConfigInterface;
13-
use Psr\Log\LoggerInterface;
1412

1513
/**
1614
* The product gallery upload controller
17-
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
1815
*/
1916
class Upload extends \Magento\Backend\App\Action implements HttpPostActionInterface
2017
{
@@ -55,32 +52,19 @@ class Upload extends \Magento\Backend\App\Action implements HttpPostActionInterf
5552
*/
5653
private $productMediaConfig;
5754

58-
/**
59-
* @var UploadResizeConfigInterface
60-
*/
61-
private $imageUploadConfig;
62-
63-
/**
64-
* @var LoggerInterface
65-
*/
66-
private $_logger;
67-
6855
/**
6956
* @param \Magento\Backend\App\Action\Context $context
7057
* @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
7158
* @param \Magento\Framework\Image\AdapterFactory|null $adapterFactory
7259
* @param \Magento\Framework\Filesystem|null $filesystem
7360
* @param \Magento\Catalog\Model\Product\Media\Config|null $productMediaConfig
74-
* @param UploadResizeConfigInterface|null $imageUploadConfig
75-
* @throws \Magento\Framework\Exception\FileSystemException
7661
*/
7762
public function __construct(
7863
\Magento\Backend\App\Action\Context $context,
7964
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
8065
\Magento\Framework\Image\AdapterFactory $adapterFactory = null,
8166
\Magento\Framework\Filesystem $filesystem = null,
82-
\Magento\Catalog\Model\Product\Media\Config $productMediaConfig = null,
83-
UploadResizeConfigInterface $imageUploadConfig = null
67+
\Magento\Catalog\Model\Product\Media\Config $productMediaConfig = null
8468
) {
8569
parent::__construct($context);
8670
$this->resultRawFactory = $resultRawFactory;
@@ -90,8 +74,6 @@ public function __construct(
9074
->get(\Magento\Framework\Filesystem::class);
9175
$this->productMediaConfig = $productMediaConfig ?: ObjectManager::getInstance()
9276
->get(\Magento\Catalog\Model\Product\Media\Config::class);
93-
$this->imageUploadConfig = $imageUploadConfig
94-
?: ObjectManager::getInstance()->get(UploadResizeConfigInterface::class);
9577
}
9678

9779
/**
@@ -115,12 +97,6 @@ public function execute()
11597
$result = $uploader->save(
11698
$mediaDirectory->getAbsolutePath($this->productMediaConfig->getBaseTmpMediaPath())
11799
);
118-
// Resize the image if needed
119-
$this->processImage(
120-
$imageAdapter,
121-
$mediaDirectory->getAbsolutePath($this->productMediaConfig->getBaseTmpMediaPath()),
122-
$result['file']
123-
);
124100
$this->_eventManager->dispatch(
125101
'catalog_product_gallery_upload_image_after',
126102
['result' => $result, 'action' => $this]
@@ -148,48 +124,6 @@ public function execute()
148124
return $response;
149125
}
150126

151-
/**
152-
* Resize the image
153-
*
154-
* @param \Magento\Framework\Image\AdapterFactory $imageAdapter
155-
* @param string $path
156-
* @param string $file
157-
* @return bool
158-
*/
159-
private function processImage($imageAdapter, $path, $file): bool
160-
{
161-
try {
162-
$filePath = $path . DIRECTORY_SEPARATOR . $file;
163-
164-
// Open the image file
165-
$imageAdapter->open($filePath);
166-
167-
// Get current dimensions
168-
$imageWidth = $imageAdapter->getOriginalWidth();
169-
$imageHeight = $imageAdapter->getOriginalHeight();
170-
171-
// Fetch resizing configurations
172-
$maxWidth = $this->imageUploadConfig->getMaxWidth();
173-
$maxHeight = $this->imageUploadConfig->getMaxHeight();
174-
175-
// Check if resizing is necessary
176-
if ($this->imageUploadConfig->isResizeEnabled()
177-
&& ($imageWidth > $maxWidth || $imageHeight > $maxHeight)) {
178-
// Maintain aspect ratio and resize
179-
$imageAdapter->keepAspectRatio(true);
180-
$imageAdapter->resize($maxWidth, $maxHeight);
181-
182-
// Save the resized image
183-
$imageAdapter->save($filePath);
184-
}
185-
186-
return true;
187-
} catch (\Exception $e) {
188-
$this->_logger->error($e->getMessage());
189-
return false;
190-
}
191-
}
192-
193127
/**
194128
* Get the set of allowed file extensions.
195129
*
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
/**
3+
* Copyright © Magento, Inc. All rights reserved.
4+
* See COPYING.txt for license details.
5+
*/
6+
declare(strict_types=1);
7+
8+
namespace Magento\ConfigurableProduct\ViewModel;
9+
10+
use Magento\Backend\Model\Image\UploadResizeConfigInterface;
11+
12+
/**
13+
* Get configuration values for frontend image uploader.
14+
*/
15+
class uploadResizeConfigValue implements \Magento\Framework\View\Element\Block\ArgumentInterface
16+
17+
{
18+
/**
19+
* @var UploadResizeConfigInterface
20+
*/
21+
private UploadResizeConfigInterface $uploadResizeConfig;
22+
23+
/**
24+
* @param UploadResizeConfigInterface $uploadResizeConfig
25+
*/
26+
public function __construct(
27+
UploadResizeConfigInterface $uploadResizeConfig
28+
) {
29+
$this->uploadResizeConfig = $uploadResizeConfig;
30+
}
31+
32+
/**
33+
* Get maximal width value for resized image
34+
*
35+
* @return int
36+
*/
37+
public function getMaxWidth(): int
38+
{
39+
return $this->uploadResizeConfig->getMaxWidth();
40+
}
41+
42+
/**
43+
* Get maximal height value for resized image
44+
*
45+
* @return int
46+
*/
47+
public function getMaxHeight(): int
48+
{
49+
return $this->uploadResizeConfig->getMaxHeight();
50+
}
51+
52+
/**
53+
* Get config value for frontend resize
54+
*
55+
* @return bool
56+
*/
57+
public function isResizeEnabled(): bool
58+
{
59+
return $this->uploadResizeConfig->isResizeEnabled();
60+
}
61+
62+
63+
}

app/code/Magento/ConfigurableProduct/view/adminhtml/layout/catalog_product_wizard.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
<item name="modal" xsi:type="string">configurableModal</item>
5959
<item name="dataScope" xsi:type="string">productFormConfigurable</item>
6060
</argument>
61+
<argument name="view_model" xsi:type="object">Magento\ConfigurableProduct\ViewModel\uploadResizeConfigValue</argument>
6162
</arguments>
6263
</block>
6364
<block class="Magento\ConfigurableProduct\Block\Adminhtml\Product\Steps\Summary" name="step4" template="Magento_ConfigurableProduct::catalog/product/edit/attribute/steps/summary.phtml">

app/code/Magento/ConfigurableProduct/view/adminhtml/templates/catalog/product/edit/attribute/steps/bulk.phtml

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,13 @@
77
// phpcs:disable PHPCompatibility.Miscellaneous.RemovedAlternativePHPTags.MaybeASPOpenTagFound
88
/* @var $block \Magento\ConfigurableProduct\Block\Adminhtml\Product\Steps\Bulk */
99
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
10+
/** @var $viewModel uploadResizeConfigValue */
1011
/** @var \Magento\Framework\Escaper $escaper */
11-
?>
1212

13+
use Magento\ConfigurableProduct\ViewModel\uploadResizeConfigValue;
14+
15+
$viewModel = $block->getViewModel();
16+
?>
1317
<?php
1418
/** @var \Magento\Framework\Json\Helper\Data $jsonHelper */
1519
$jsonHelper = $block->getData('jsonHelper');
@@ -767,7 +771,10 @@ $uploadUrl = $block->getUrl('catalog/product_gallery/upload');
767771
"component": "Magento_ConfigurableProduct/js/variations/steps/bulk",
768772
"appendTo": "<?= /* @noEscape */ $block->getParentComponentName() ?>",
769773
"noImage": "<?= /* @noEscape */ $block->getNoImageUrl() ?>",
770-
"variationsComponent": "<?= /* @noEscape */ $block->getData('config/form')?>.configurableVariations"
774+
"variationsComponent": "<?= /* @noEscape */ $block->getData('config/form')?>.configurableVariations",
775+
"isResizeEnabled": <?= /* @noEscape */ $viewModel->isResizeEnabled() ?>,
776+
"maxWidth": <?= /* @noEscape */ $viewModel->getMaxWidth() ?>,
777+
"maxHeight": <?= /* @noEscape */ $viewModel->getMaxHeight() ?>
771778
}
772779
}
773780
}

app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/variations/steps/bulk.js

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ define([
3535
notificationMessage: {
3636
text: null,
3737
error: null
38+
},
39+
options: {
40+
isResizeEnabled: false,
41+
maxWidth: 1920,
42+
maxHeight: 1080
3843
}
3944
},
4045

@@ -46,7 +51,7 @@ define([
4651
},
4752

4853
/** @inheritdoc */
49-
initialize: function () {
54+
initialize: function (config) {
5055
var self = this;
5156

5257
this._super();
@@ -72,6 +77,13 @@ define([
7277
}
7378
});
7479

80+
// Retrieve configuration passed from .phtml
81+
if (config) {
82+
this.options.isResizeEnabled = config.isResizeEnabled || false;
83+
this.options.maxWidth = config.maxWidth || 1920;
84+
this.options.maxHeight = config.maxHeight || 1080;
85+
}
86+
7587
this.variationsComponent(function (variationsComponent) {
7688
this.sections().price.currencySymbol = variationsComponent.getCurrencySymbol();
7789
}.bind(this));
@@ -165,6 +177,8 @@ define([
165177
});
166178

167179
this.initCountVariations();
180+
// Explicitly bind the `bindGalleries` method to the component's context
181+
this.bindGalleries = this.bindGalleries.bind(this);
168182
this.bindGalleries();
169183
},
170184

@@ -368,6 +382,7 @@ define([
368382
* Bind galleries.
369383
*/
370384
bindGalleries: function () {
385+
var self = this; // Save the correct context of 'this'
371386
$('[data-role=bulk-step] [data-role=gallery]').each(function (index, element) {
372387
var gallery = $(element),
373388
uploadInput = $(gallery.find('.uploader'))[0],
@@ -385,6 +400,8 @@ define([
385400
let targetElement = uploadInput,
386401
fileId = null,
387402
arrayFromObj = Array.from,
403+
allowedExt = ['jpeg', 'jpg', 'png', 'gif'],
404+
allowedResize = false,
388405
options = {
389406
proudlyDisplayPoweredByUppy: false,
390407
target: targetElement,
@@ -425,6 +442,8 @@ define([
425442
id: fileId
426443
}
427444
});
445+
// check if file is allowed to upload and resize
446+
allowedResize = $.inArray(currentFile.extension?.toLowerCase(), allowedExt) !== -1;
428447

429448
// code to allow duplicate files from same folder
430449
const modifiedFile = {
@@ -445,6 +464,20 @@ define([
445464
// initialize Uppy upload
446465
uppy.use(Uppy.Dashboard, options);
447466

467+
// Use 'self.options' to access component options
468+
if (self.options.isResizeEnabled) {
469+
uppy.use(Uppy.Compressor, {
470+
maxWidth: self.options.maxWidth,
471+
maxHeight: self.options.maxHeight,
472+
quality: 0.92,
473+
beforeDraw() {
474+
if (!allowedResize) {
475+
this.abort();
476+
}
477+
}
478+
});
479+
}
480+
448481
// drop area for file upload
449482
uppy.use(Uppy.DropTarget, {
450483
target: dropZone,
@@ -462,7 +495,6 @@ define([
462495
endpoint: uploadUrl,
463496
fieldName: 'image'
464497
});
465-
466498
uppy.on('upload-success', (file, response) => {
467499
if (response.body && !response.body.error) {
468500
gallery.trigger('addItem', response.body);

0 commit comments

Comments
 (0)