Magento2 – Base, Small & Thumbnail Image Not Setting Programmatically

imagemagento2product

I am using below code to set the image as base,small and thumbnail, but it is not working.

$productRepository = $this->_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$product = $productRepository->get($sku);
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), true, false);

Can anyone suggest, what is wrong with the code

Best Answer

As far as I know, Magento 2 has a test to set Base, Small and Thumbnail image dev/tests/integration/testsuite/Magento/Sitemap/_files/sitemap_products.php.

We can follow the logic of this and create your own. An simple example:

$obj = \Magento\Framework\App\ObjectManager::getInstance();

/** @var \Magento\Framework\Filesystem $filesystem */
$filesystem = $obj->create('Magento\Framework\Filesystem');
/** @var \Magento\Framework\Filesystem\Directory\WriteInterface $mediaDirectory */
$mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$mediaPath = $mediaDirectory->getAbsolutePath();

//Sample product id
$productId = 1;
$model = $obj->create('Magento\Catalog\Model\Product');
$product = $model->load($productId);
$product->setImage(
            $mediaPath . '/magento_image.png'
        )
        ->setSmallImage(
            $mediaPath . '/magento_image_small.png'
        )
        ->setThumbnail(
            $mediaPath . '/magento_image_thumb.png'
        )
        ->addImageToMediaGallery(
          $mediaPath . '/first_magento_image.png',
            null,
            false,
            false
        )->addImageToMediaGallery(
            $mediaPath . '/second_image.png',
            null,
            false,
            false
        )
        ->save();

We can try to test my code with playground and here.