Magento 2 Update product image programetically
<?php
//increase the max execution time
@ini_set('max_execution_time', -1);
//memory_limit
@ini_set('memory_limit', -1);
error_reporting(E_ALL);
ini_set('display_errors', '1');
use \Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$instance = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product_collections = $instance->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $product_collections->create();
foreach ($collections as $product)
{
if ($product->getId() == 2052)
{
$product = $objectManager->create('\Magento\Catalog\Model\Product')
->load($product->getId());
$images = $product->getMediaGalleryImages();
$image = $images->getFirstItem();
$imageUrl = $image->getFile();
echo $imagePath = '/pub/media/catalog/product' . $imageUrl;
$product->setStoreId(0);
$product->setImage($imageUrl);
$product->setSmallImage($imageUrl);
$product->setThumbnail($imageUrl);
$product->save();
echo "Done";
die;
}
}
?>
Comments
Post a Comment