Magento 2, being popular, often hosts stores migrating from other platforms. It requires to import product images from URL in Magento 2. By default, Magento 2 handles image imports well but they should be located in your server only. But when it comes to importing the product image from an external URL, you can use the below solution.
The below service can be included anywhere required and its execute method will be called with the following params:
- $product – loaded product instance, the image will be added to it
- $imageUrl – external image URL
- $visible – an image will be hidden by default. You may make it visible, simply by passing the boolean value “true”;
- $imageType – an array, optional param, where you can specify whether to set an image as the main image, a small image or a thumbnail or any combination of those.
The post offers the solution to easily import product images from the external URL in Magento 2 store.
Method To Import Product Images From URL In Magento 2:
Create ImportImageService.php Class in app/code/[Vendor]/[Module]/Service folder and add the following code:
<?php namespace [Vendor]\[Module]\Service; use Magento\Catalog\Model\Product; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem\Io\File; class ImportImageService { protected $directoryList; protected $file; public function __construct(DirectoryList $directoryList,File $file) { $this->directoryList = $directoryList; $this->file = $file; } public function execute($product, $imageUrl, $visible = false, $imageType = []) { $tmpDir = $this->getMediaDirTmpDir(); $this->file->checkAndCreateFolder($tmpDir); $newFileName = $tmpDir . baseName($imageUrl); $result = $this->file->read($imageUrl, $newFileName); if ($result) { $product->addImageToMediaGallery($newFileName, $imageType, true, $visible); } return $result; } protected function getMediaDirTmpDir() { return $this->directoryList->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp'; } }
The above solution proves as a time-saver while carrying out the data migration to Magento 2.
Do share the post with fellow developers via social media.
Thank you.