6

I've placed a image file in the folder "pub/media/import" for product image, and run the below script, but I got an error message.

$fullImagePath = "pub/media/import/icn_status.png";
echo $fullImagePath;
if (file_exists($fullImagePath)) {
    try {

        $simple_product->addImageToMediaGallery($fullImagePath, array('image'), false);
    } catch (Exception $e) {
        echo $e->getMessage();
    }
} else {
    echo 'Can not find image';
}

ERROR:

[Magento\Framework\Exception\LocalizedException]

The image does not exist.
  • I may be wrong but don't you have to call $simple_product->save(); after adding the images to the product ? – Raphael at Digital Pianism Feb 16 '16 at 9:40
  • thank you for your reply, the $simple_product is created by magento objectManager $simple_product = $this->objectManger->create('\Magneto\Catalog\Model\Product'); – P.S. Feb 18 '16 at 3:34
6

Thanks,

I've checked there is no problem on my code. The problem is file location. I just amended the image file path, the problem has been solved.

$fullImagePath = "/import/icn_status.png";
echo $fullImagePath;
if (file_exists("pub/media".$fullImagePath)) {
    try {
        $simple_product->addImageToMediaGallery($fullImagePath, array('image'), false);
    } catch (Exception $e) {
        echo $e->getMessage();
    }
} else {
    echo 'Can not find image';
}

P.S.

1

Just to add to P.S. answer and explain why the file path should be relative to media folder:

addImageToMediaGallery calls Model\Product\Gallery\Processor.php::addImage

 $file = $this->mediaDirectory->getRelativePath($file);
 if (!$this->mediaDirectory->isFile($file)) {
      throw new LocalizedException(__('The image does not exist.'));
 }

You can do a debug of the $file, and then keep digging which will eventually bring you to Magento\Framework\Filesystem\Directory\Read

Particularly this line 219: $this->driver->getAbsolutePath($this->path, $path)

Now, if your path was "/pub/media/import/icn_status.png" then by debugging the result of getAbsolutePath call, you will get something like this:

/yoursite/public_html/pub/media/pub/media/import/icn_status.png

So your path is prefixed with the full server path to your media folder.

Hope it makes it more clear now.

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.