5

During edit product from front-end I need to remove images of the product gallery which are checked by the user to remove it.

5
  • How you can edit product from Front End?
    – Jackson
    Oct 6 '16 at 7:31
  • We are creating a panel on frontend where some user can create/edit/delete the products. But during editing we are facing problem in removing the images of product. Oct 6 '16 at 7:36
  • Please update the question & if possible put the code & error so can help out
    – Jackson
    Oct 6 '16 at 7:39
  • We are not getting any error, we just want to discover that what code we need to implement to remove image of a particular product Oct 6 '16 at 9:24
  • How about your issue? Oct 18 '16 at 0:07
10

Below code working fine for me to remove Image Magento 2.

Using Product ID:

$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productNewId);
$imageProcessor = $objectManager->create('\Magento\Catalog\Model\Product\Gallery\Processor');
$images = $product->getMediaGalleryImages();
foreach($images as $child){
    $imageProcessor->removeImage($product, $child->getFile());
}   

Hope it helps to you

3
  • 2
    You shouldn't use ObjectManager... apart from that, your code is good.
    – leedch
    Jan 4 '18 at 14:50
  • this gives me integrity constraint violations Sep 15 '18 at 19:43
  • Not working for disable images Nov 21 '19 at 10:53
8

We can use \Magento\Catalog\Model\ProductFactory to get media gallery. We also need to declare the \Magento\Catalog\Api\ProductRepositoryInterface class which helps us to save the existing product.

We can use Object Manager directly, however, this way isn't good. It's better that we should inject these class in the constructor.

/**@var \Magento\Catalog\Model\ProductFactory **/
protected $product;

/**@var \Magento\Catalog\Api\ProductRepositoryInterface **/
protected $productRepository;

public function __construct(
   ......
   \Magento\Catalog\Model\ProductFactory $product,
   \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
   ......
)
{
  $this->product = $product;
  $this->productRepository = $productRepository;
}

In your custom method:

//Product id
$productId = 12;
$product = $this->product->create();

$existingMediaGalleryEntries = $product->load($productId)->getMediaGalleryEntries();

foreach ($existingMediaGalleryEntries as $key => $entry) {
    //We can add your condition here
    unset($existingMediaGalleryEntries[$key]);
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
$this->productRepository->save($product);

Should take a look at the Unit test:

--vendor/magento/module-catalog/Test/Unit/Model/ProductTest.php
--vendor/magento/module-catalog/Test/Unit/Model/ProductRepositoryTest.php
--vendor/magento/module-catalog/Test/Unit/Model/Product/Gallery/GalleryManagementTest.php

10
  • using this code when i add other base image programmatically that image is not set as base image so how to remove all base,thumbnail,small image ?
    – ND17
    Nov 24 '16 at 10:47
  • @ND17 you want to remove all base, thumbnail, small images? My code above cannot help you anymore? Nov 24 '16 at 10:50
  • your code is remove all images but when i try to save other image as base image, it is not set as base image and if i remove all images and save same image which i am removing than that image is set as base image
    – ND17
    Nov 24 '16 at 10:53
  • this is happens beacuse cache folder is exist in media\catalog\product
    – ND17
    Nov 24 '16 at 11:20
  • @KhoaTruongDinh i tried above solution but it fires constraint exception? Mar 22 '18 at 7:54
2

For me it finally worked based on this article: https://www.mageplaza.com/devdocs/add-images-to-product-programmatically-magento-2.html

    $gallery = $_product->getMediaGalleryImages();
    if (count($gallery) > 0) {
        foreach($gallery as $image){
            $this->productGallery->deleteGallery($image->getValueId());
        }
        $_product->setMediaGalleryEntries([]);
        $_product->save();
    }

Where productGallery is an instance of \Magento\Catalog\Model\ResourceModel\Product\Gallery

I hope it helps someone

1
  • Thanks, only your code works after hours of search!! =)
    – Luis
    Jul 3 at 4:15
0

I was working on similar task, I am sharing my code, hope it would help others too.

Fist initialization in constructor

protected $productModel;
protected $imageProcessor;

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

Now you can use it in your function

$product = $this->productModel->load($productId);
$gallery = $product->getMediaGalleryImages();
foreach($gallery as $image){
    $this->imageProcessor->removeImage($product,$image->getFile());
}
$product->save();

This should work

0
Delete the specfic images 
    <?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    ini_set('memory_limit', '-1');
    ini_set('max_execution_time', 0); 
    set_time_limit(0);
    error_reporting(E_ALL);
    use Magento\Framework\App\Bootstrap;
    require __DIR__ . '/app/bootstrap.php';
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $obj = $bootstrap->getObjectManager();
    $state = $obj->get('Magento\Framework\App\State');
    $state->setAreaCode('frontend');
    
    //Instance of object manager
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
    //skus
    // $productArray = array("7750087","7750100");
    $file = fopen('deLId.csv', 'r', '"'); // set path to the CSV file
    $header = fgetcsv($file); // get data headers and skip 1st row
    while ( $row = fgetcsv($file, 40000, ",") ) {
        $data_count = count($row);
            if ($data_count < 1) {
                continue;
            }
        $data = array();
        $data = array_combine($header, $row);
        $sku=$data["sku"];
        $productIds=$data["id"];
        $productSkus=explode(',',$productIds);
        // $productSkus=implode(',',$productSkus);
        // print_r(gettype($productSkus));
        // echo gettype($productSkus).PHP_EOL;
        // die();
    
       if (!empty($productSkus)) {
           foreach($productSkus as $key=>$productData){
    
               $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productData);
               $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
               $existingMediaGalleryEntries = $product->getMediaGalleryEntries();
    
                 foreach ($existingMediaGalleryEntries as $key => $entry){
                    if (!empty($entry)) {   
                        unset($existingMediaGalleryEntries[$key]);
                    }else{
                        echo "already deleted";
                    }
                 }
    
                $product->setMediaGalleryEntries($existingMediaGalleryEntries);
                $productRepository->save($product);
    
                echo "Product Image has been deleted for ".$productIds." successfully"." against ".$sku.PHP_EOL;
    
            }
       }
    }
    echo "Yahooooo";
    
     ?>
0

run below script for remove images from all products

  <?php
    error_reporting(1);
    ini_set('max_execution_time', 0);
    use \Magento\Framework\App\Bootstrap;
    require __DIR__ . '/app/bootstrap.php';
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $instance = \Magento\Framework\App\ObjectManager::getInstance();
    $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
    $state = $objectManager->get('\Magento\Framework\App\State');
    
    $state->setAreaCode('frontend');
    $productcollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');   
    //$productcollection->addAttributeToFilter('type_id', array('eq' => 'simple'));
    //$productcollection->addAttributeToFilter('status', array('eq' => '1'));
    //$productcollection->addAttributeToFilter('visibility', array('eq' => '4'));
    if(count($productcollection)){
        $i=0;
        foreach($productcollection as $productdata){        
        $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productdata->getEntityId());
        $productRepo = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
        $exiMediaGallery = $product->getMediaGalleryEntries();
            
        foreach ($exiMediaGallery as $key => $val) {
            unset($exiMediaGallery [$key]);
        }
            $product->setMediaGalleryEntries($exiMediaGallery);
            $productRepo->save($product);
            echo "\n".$product->getSku()."....".$i;
            $i++;
        }
    }else{
    echo 'No Product Found';
    }
    
    ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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