Hello Magento Friends,
Today I am here with another Magento 2 solution. How to Set Product Image using Image URL Link Programmatically in Magento 2?
The product image helps to create an impression on the buyer. With online shopping, customers cannot feel the products, and thus product image plays a vital role in purchase decisions.
In Magento 2, you can set product images using the image URL. But before that, you need to Get Product Image URL in Magento 2.
Let’s jump into How to Set Product Image using Image URL Link Programmatically in Magento 2.
Steps to Set Product Image using Image URL Link Programmatically in Magento 2:
Step 1: Create a file in your Magento root directory at the below path
magento_root_directory\Uploadimagefile.php
Then add the code as follows
<?php use Magento\Framework\AppInterface; try { require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try { $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('\Magento\Framework\App\State'); $appState->setAreaCode('frontend'); $product_id=1; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id); // Enter Your image URL here saveimage($product,"https://magecomp.com/media/logo/websites/1/Magecomp_Logo_251x51.png"); $product->save(); echo "Product Save with images"; } catch(\Exception $e) { echo "Error : ".$e->getMessage(); } function saveimage($product, $imageUrl, $visible = false, $imageType = []) { $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $file = $objectManager->get('Magento\Framework\Filesystem\Io\File'); $directoryList = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList'); $tmpDir = $directoryList->getPath(Magento\Framework\App\Filesystem\DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp'; $file->checkAndCreateFolder($tmpDir); $newFileName = $tmpDir . baseName($imageUrl); $result = $file->read($imageUrl, $newFileName); if ($result) { $product->addImageToMediaGallery($newFileName, array('image', 'small_image', 'thumbnail'), false, $visible); } return $result; } ?>
Step 2: After the above step, you will need to run the below-given URL.
https://yourdomain.com/Uploadimagefile.php
Note: Please use the image URL containing the file with a specific format.
Example: https://magecomp.com/media/logo/websites/1/Magecomp_Logo_251x51.png
Conclusion:
This way, you can Set Product Image using Image URL Link Programmatically in Magento 2. If you face any complications while performing the above steps, share them with me through the comment box.
Happy Coding!