Magento 2 Add Image To Product Programmatically

If you want to add an image to product, you can use the following code snippet which explains how to assign an image with multiple sizes to a product programmatically. If you want to create simple product, please follow the link.

// Adding An Image to product
$productId = 1;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('\Magento\Catalog\Model\Product');

$imagePath = "test.jpg"; // Here you need to provide the path of the image
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);

Leave a Reply