The method below looks for images in the folder “/pub/media/import/” and, if found, they get imported for the product.
protected function importImages(\Magento\Catalog\Model\Product $product)
{
$imageName = $product->getSku();
$imageFolder = strtolower(explode('_', $imageName)[0]) . "/";
$dir = $this->_objectManager->get('\Magento\Framework\App\Filesystem\DirectoryList');
$mediaImportFolder = $dir->getPath(DirectoryList::MEDIA);
if($this->isSetFlag('remove_existing_images')) {
// remove images
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {
unset($existingMediaGalleryEntries[$key]);
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
$this->_productRepositoryInterface->save($product);
}
$product->setMediaGallery(array('images'=>array (), 'values'=>array ()));
$i = $foundImages = 0;
while($i < 10) {
$i++;
$imagePath = 'import/' . $imageFolder . $imageName . "_IMAGE" . $i . ".jpg";
$imageAbsolutePath = $mediaImportFolder . '/' . $imagePath;
if(!$imageAbsolutePath = $this->fileExists($imageAbsolutePath)) {
continue 1;
}
$flags = ($foundImages == 0) ? ['image','thumbnail','small_image'] : [];
$product->addImageToMediaGallery($imageAbsolutePath, $flags, false, false);
$this->log(" - Image {$imagePath} imported with success for the product SKU {$product->getSku()}");
$foundImages++;
}
if($foundImages == 0) {
$this->log(" - No images found for the product SKU {$product->getSku()}");
}
return $this;
}