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

  • still not working? Aug 10, 2016 at 15:51
  • Thanks for the Answer,Let me try by this weekend and let you know
    – user2520
    Aug 11, 2016 at 5:17
  • How about your current issue? Aug 24, 2016 at 15:00

2 Answers 2


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);
            $mediaPath . '/magento_image.png'
            $mediaPath . '/magento_image_small.png'
            $mediaPath . '/magento_image_thumb.png'
          $mediaPath . '/first_magento_image.png',
            $mediaPath . '/second_image.png',

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


This code builds the image. You can either set the type on one image for all images types or individually:

            $mgEntry =
            $fileok = @fopen($imagePath, "r");

            if ($fileok) {
                $fileData = file_get_contents($imagePath);
                if ($fileData) {
                    $imageLabel = 'label_value';
          //          $mgEntry->setTypes(["image", "small_image", "thumbnail"]);
                    $mgEntry->setTypes([$type]); //thumbnail etc
                    $imageData = base64_encode($fileData);
                    $imageContent =
                    array_push($mgEntries, $mgEntry);
            } else {                
                $error = error_get_last();
                $this->logger->info("not able to get image file because {$error['message']}");

Add each of the $mgEntry values to an array, and then add the array to the product

$magentoProduct->setMediaGalleryEntries([mgEntry array]);   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.