How to delete a product's base image programatically and then set the next image as base?

$product = $objectManager->create('Magento\Catalog\Model\Product')->load($result1[0]['mage_product_id']);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {
	unset($existingMediaGalleryEntries[$key]);
}

$product->setMediaGalleryEntries($existingMediaGalleryEntries);

$productRepository->save($product);
$product->addImageToMediaGallery($image_path, array('image', 'small_image', 'thumbnail'), false, false);
//print_r($product);
$product->save();

Hello ,
In Above code,we can delete whole image list , but i want to delete single image as per requirement and after that assign the base image to next image after delete.

A post was split to a new topic: «addImageToMediaGallery() ‘image’, ‘small_image’, ‘thumbnail’ not selected in image»

Hello
here some modification of your code
try this may be can help you

$product = $objectManager->create('Magento\Catalog\Model\Product')->load($result1[0]['mage_product_id']);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$mediatypeArray = array('image');
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {
	if($entry['image'] == $mediatypeArray)
	unset($existingMediaGalleryEntries[$key]);
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
//here you  use of \Magento\Catalog\Model\Product\Gallery\Processor class and set 
$this->imageProcessor->clearMediaAttribute($product,$mediatypeArray);
$productRepository->save($product);
$product->addImageToMediaGallery($image_path, array('image'), true, false);
//print_r($product);
$product->save();

Thank You

1 Like