Magento – How to save product gallery image with param image is url, in Magento-2

gallery-imagemagento2product-imagesproducts

In Magento 2, I have created an extension, syncs products with another store. I have the data image_url which is in the following format ,

["images" => ["0" => "http://image_url.jng", "1" => "http://image_url_1.jng"];

So how to save these as product gallery image in magento 2 with this data?

Best Answer

Magento 2 doesn't take gallery images directly from url, so first you will need to download them to local storage preferably pub/media/your_folder . And then simply add them as following.[ Please use dependency injection in your code ]

    // Instance of object manager
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $productId = ; // Id of product
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
    $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface'); 
    /*Add Images To The Product*/
    $imagePath = "sample.png"; // path of the image
    $product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
    $product->save();

Reference Url->https://stackoverflow.com/questions/40259303/add-remove-image-programmatically-to-product-magento2

Related Topic