I am having image url as


which I need to set for my products. I have tried by setting product image url:

$productId = 1;
$product = $this->_product->load(1);
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {

public function saveImg()
   $imageUrl = 'http://s6.favim.com/610/150425/adorable-animal-cat-cute-Favim.com-2680526.jpg'; 
   $product->addImageToMediaGallery($imageUrl, array('image','small_image', 'thumbnail'), false, false);

But this code displays error as image not found. What I need to do to set product image as url?


Pleaes try with following code

use Magento\Framework\App\Action\Context;

class Createproduct extends \Magento\Framework\App\Action\Action {

    protected $directoryList;
    protected $file;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
        \Magento\Framework\Filesystem\Io\File $file) {

        $this->_resultpageFactory = $pageFactory;
        $this->directoryList = $directoryList;
        $this->file = $file;
        return parent::__construct($context);

    protected function getMediaDirTmpDir()
        return $this->directoryList->getPath($this->directoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;

    public function setImage($product, $imageUrl, $visible = false, $imageType = [])
        $tmpDir = $this->getMediaDirTmpDir();


        $newFileName = $tmpDir . baseName($imageUrl);

        $result = $this->file->read($imageUrl, $newFileName);
        if ($result) {
            $product->addImageToMediaGallery($newFileName, $imageType, true, $visible);
        return $result;

    public function execute() {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('\Magento\Catalog\Model\Product')->load(1);
        $imagePath = "https://domain.com/image.jpg"; // path of the image
            $this->setImage($product, $imagePath, false, $imageType = ['image', 'small_image', 'thumbnail']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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