Here is the code snippet I use to add an image in a product's media gallery :
$sku = 'product-example-sku';
$image_url = 'http://example.com/image.jpg';
$image_ext = pathinfo($image_url, PATHINFO_EXTENSION);
$image_path = '/import/' . $sku . '.' . $image_ext;
file_put_contents('pub/media' . $image_path, file_get_contents($image_url));
if (file_exists('pub/media' . $image_path))
{
try
{
$product->addImageToMediaGallery($image_path, array('image'), true, false);
}
catch (\Exception $e)
{
echo '[ERROR] Image import failed for product "' . $sku . '": ' . $e->getMessage();
}
}
$this->_productRepository->save($product);
I am sure that the image is actually downloaded and moved successfully. But when I try to save the product after adding the image, this exception is thrown by Magento:
Exception #0 (Exception): Notice: Undefined index: media_type in /var/www/<website>/vendor/magento/module-catalog/Model/Product.php on line 2527
I can't find in the Magento core's code how to solve my problem.
Any help would be appreciated.