Magento – Change product image base image programmatically Magento 2

magento2.3.2product-images

I want to change bulk product image base image programmatically Magento 2

Best Answer

Please make changes as per your requirement in below script and run script from root

<?php
ini_set('memory_limit', '512M');
set_time_limit(0);
require __DIR__ . '/app/bootstrap.php';
$bootstrap     = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$dir = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create(); // you can load product collection as per your requirement here 
$imagePath = $dir->getPath('media')."/yourimage.jpg"; // Your image should be on pub/media path
$imageType = ['image']; //this is only for base image
// $imageType = ['image', 'small_image', 'thumbnail']; //this is for all images

if($collection->getSize()) {
    foreach ($collection as $product) {
        if($product->getId()) {
            if(file_exists($imagePath)) {
                $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
                $product->addImageToMediaGallery($imagePath, $imageType, false, false);
                $product->save();
            }
        }
    }
} 

Hope this will help you!

Related Topic