How to Set Product Image using Image URL Link Programmatically in Magento 2?

 <?php

use Magento\Framework\AppInterface;

try

{

    require_once __DIR__ . '/app/bootstrap.php';

catch (\Exception $e) 

{

    echo 'Autoload error: ' . $e->getMessage();

    exit(1);

}

try

{

       $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

       $objectManager = $bootstrap->getObjectManager();

       $appState = $objectManager->get('\Magento\Framework\App\State');

       $appState->setAreaCode('frontend');

       $product_id=1;

       $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

       $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

       

       // Enter Your image URL here

       saveimage($product,"https://magecomp.com/media/logo/websites/1/Magecomp_Logo_251x51.png");

       $product->save();

       echo "Product Save with images";

}

catch(\Exception $e)

{

echo "Error : ".$e->getMessage();

}


function saveimage($product, $imageUrl, $visible = false, $imageType = [])

{

       $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

       $file = $objectManager->get('Magento\Framework\Filesystem\Io\File');

       $directoryList = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');

       $tmpDir = $directoryList->getPath(Magento\Framework\App\Filesystem\DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp';

       $file->checkAndCreateFolder($tmpDir);

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

       $result = $file->read($imageUrl, $newFileName);

       if ($result)

       {

                $product->addImageToMediaGallery($newFileName,  array('image', 'small_image', 'thumbnail'), false, $visible);

       }

       return $result;

}

?>

Comments

Popular posts from this blog

Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid in Magento 2

How to Update Product Stock Programmatically in Magento 2

How to Set and Get Cookie in Magento 2