Hello and this is my code:

$imgURL = 'path/to/my/image.png';
$fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
$mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();

$product->addImageToMediaGallery($mediaPath.'catalog/product'.$data['thumbnail_image'],['thumbnail', 'swatch'], false, false);

What I want to achive, is to assign programmatically an image and set it as a thumbnail. The above code, uploads the image, but it's role: the thumbnail and swatch are not selected. Not sure why ? See img: enter image description here

Can you tell me what am i doing wrong ? thank you

1 Answer 1


You don't need to set explicitly the thumbnail, the following line is enough:

$product->addImageToMediaGallery($mediaPath.'catalog/product'.$data['thumbnail_image'],['thumbnail', 'swatch'], false, false);

As for the swatch image, you have it wrong in the array, it should be "swatch_image" instead of "swatch". The following media types are available:

  • image
  • small_image
  • thumbnail
  • swatch_image

You should also consider resizing images after setting them this way by using Magento\Catalog\Helper\Image:

$this->imageHelper->init($product, 'product_thumbnail_image');
$this->imageHelper->resize($width, $height);

Also, check the etc/view.xml from your theme for more image ids ('wishlist_thumbnail', 'mini_cart_product_thumbnail', etc)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.