0

I need to update Product Images programmatically. I have created custom media type attribute like:

Image1, Image2, Image3

I need to delete Image2 from MediaGalleryEntries and reassign Image3 to Image2.

Magento\Catalog\Model\Product\Gallery\GalleryManagement

I am checking GalleryManagement class as well but not able to getting, how to swap images and update ?

2 Answers 2

2

I have completed the task using the below functionlity:

\Magento\Catalog\Model\Product\Gallery\Processor Class Provides all the functions for Images functionlity

public function __construct(
    ....     
    \Magento\Catalog\Model\Product\Gallery\Processor $imageProcessor,
    ....     
) {
    ....     
    $this->imageProcessor       = $imageProcessor;
    ....     
}

We can Remove the assigned media attribute from image using the below code. After media attribute will be removed from image but image still exist as product gallery.

$this->imageProcessor->clearMediaAttribute($product, 'image2');

After that we can get Another Attribute Image path and assigned to new one.

$this->imageProcessor->setMediaAttribute($product, 'image2', '/i/m/image_3.jpg');

and remove the extra image from gallery using its path:

$this->imageProcessor->removeImage($product, '/i/m/image_2.jpg');
0

It is an old post but might help someone to update the position and label for product media.

addImageToMediaGallery looks like no possibility to change label and position. We can use image processor function like addImage() and updateImage();

public function __construct(
    ....     
    \Magento\Catalog\Model\ProductFactory $product,
    \Magento\Catalog\Model\Product\Gallery\Processor $imageProcessor,
    \Magento\Framework\Filesystem\DirectoryList $dir,
    ....     
) {
    ....     
    $this->imageProcessor       = $imageProcessor;
    $this->dir                  = $dir;
    $this->product              = $product;    
    ....     
}

// code snippest

$id = '123'; // product id
$product = $this->product->create()->load($id); 

$image_lable = 'Image Lable'; // make it dynamic as per requirement
$position = 2; // make it dynamic as per requirement

$media['file_name'] = 'your_image_name.jpg';
$imagePath = $this->dir->getPath('media') . '/img_media/' . $media['file_name'];
$mediaAttribute = array('image', 'small_image', 'thumbnail');

$imageFileUri = $this->imageProcessor->addImage(
    $product,
    $imagePath,
    $mediaAttribute,
    true, // move image from folder img_media
    false
);

// Update additional fields that are still empty after addImage call
$imageProcessor->updateImage(
    $product,
    $imageFileUri,
    [
        'label'    => $image_lable,
        'position' => $position
    ]
);
$product->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.