On magento 2.4.6, the following code worked for me:
use Magento\Catalog\Model\Product\Gallery\Processor;
.....
/** @var Processor */
protected Processor $processor;
.....
public function __construct(
.....
Processor $processor,
.....
){
.....
$this->processor = $processor;
.....
}
public function myCustomFancyMethod($sku)
{
$product = $this->productRepository->get($sku);
$fullPath = $this->getMyImages();
for ($i=0;$i < count($fullPath); $i++){
$this->processor->addImage($product, $fullPath[$i], null, false, false);
}
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
$i = 0;
foreach ($existingMediaGalleryEntries as $entry) {
$file = $entry->getFile();
$product->setStoreId(0);
if ($i === 0){
$product->setImage($file);
$product->setSmallImage($file)->setThumbnail($file);
}
$product->setData(
'media_gallery',
[
'images' => [
[
'file' => $file,
'position' => $i,
'label' => 'LabelName-'.$i,
'disabled' => 0,
'media_type' => 'image'
],
]
]
)->setCanSaveCustomOptions(true);
$product->save();
$i++;
}
}
This will set the thumbnail and base image for the first image iterated.
Of course the method: $this->getMyImages();
, I will let you to get from whereever you want the image paths.
I hope my post helped someone!
Good luck !