Skip to content

Commit 152b092

Browse files
committed
Fix Notice and Exception while adding image to product programmatically
1 parent 6c529ec commit 152b092

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

app/code/Magento/Catalog/Model/Product/Gallery/Processor.php

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
namespace Magento\Catalog\Model\Product\Gallery;
88

9+
use Magento\Framework\Api\Data\ImageContentInterface;
910
use Magento\Framework\App\Filesystem\DirectoryList;
1011
use Magento\Framework\Exception\LocalizedException;
1112
use Magento\Framework\Filesystem\DriverInterface;
@@ -183,6 +184,13 @@ public function addImage(
183184
$attrCode = $this->getAttribute()->getAttributeCode();
184185
$mediaGalleryData = $product->getData($attrCode);
185186
$position = 0;
187+
188+
$absoluteFilePath = $this->mediaDirectory->getAbsolutePath($file);
189+
$imageMimeType = mime_content_type($absoluteFilePath);
190+
$imageContent = file_get_contents($absoluteFilePath);
191+
$imageBase64 = base64_encode($imageContent);
192+
$imageName = pathinfo($destinationFile, PATHINFO_FILENAME);
193+
186194
if (!is_array($mediaGalleryData)) {
187195
$mediaGalleryData = ['images' => []];
188196
}
@@ -195,11 +203,19 @@ public function addImage(
195203

196204
$position++;
197205
$mediaGalleryData['images'][] = [
198-
'file' => $fileName,
199-
'position' => $position,
206+
'file' => $fileName,
207+
'position' => $position,
208+
'label' => '',
209+
'disabled' => (int)$exclude,
200210
'media_type' => 'image',
201-
'label' => '',
202-
'disabled' => (int)$exclude,
211+
'types' => $mediaAttribute,
212+
'content' => [
213+
'data' => [
214+
ImageContentInterface::NAME => $imageName,
215+
ImageContentInterface::BASE64_ENCODED_DATA => $imageBase64,
216+
ImageContentInterface::TYPE => $imageMimeType,
217+
]
218+
]
203219
];
204220

205221
$product->setData($attrCode, $mediaGalleryData);

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
"ext-xsl": "*",
3030
"ext-zip": "*",
3131
"lib-libxml": "*",
32+
"ext-fileinfo": "*",
3233
"braintree/braintree_php": "3.35.0",
3334
"colinmollenhour/cache-backend-file": "~1.4.1",
3435
"colinmollenhour/cache-backend-redis": "1.10.5",

0 commit comments

Comments
 (0)