6

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

asked Oct 6, 2016 at 7:28
5
  • How you can edit product from Front End? Commented Oct 6, 2016 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. Commented Oct 6, 2016 at 7:36
  • Please update the question & if possible put the code & error so can help out Commented Oct 6, 2016 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 Commented Oct 6, 2016 at 9:24
  • How about your issue? Commented Oct 18, 2016 at 0:07

7 Answers 7

12

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

answered Oct 31, 2017 at 7:28
4
  • 2
    You shouldn't use ObjectManager... apart from that, your code is good. Commented Jan 4, 2018 at 14:50
  • this gives me integrity constraint violations Commented Sep 15, 2018 at 19:43
  • Not working for disable images Commented Nov 21, 2019 at 10:53
  • Did you fixed integrity constraint violations Commented Jun 11, 2022 at 15:51
9

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

answered Oct 6, 2016 at 15:26
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 ? Commented Nov 24, 2016 at 10:47
  • @ND17 you want to remove all base, thumbnail, small images? My code above cannot help you anymore? Commented Nov 24, 2016 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 Commented Nov 24, 2016 at 10:53
  • this is happens beacuse cache folder is exist in media\catalog\product Commented Nov 24, 2016 at 11:20
  • @KhoaTruongDinh i tried above solution but it fires constraint exception? Commented Mar 22, 2018 at 7:54
9

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

answered Jul 27, 2020 at 14:29
3
  • Thanks, only your code works after hours of search!! =) Commented Jul 3, 2021 at 4:15
  • Yeah saved me a bit of manual labour there! Commented Jan 12, 2022 at 15:56
  • This should be the accepted answer. Commented Apr 19, 2022 at 14:09
2

There is all the other code you have to write but when it comes to removing images specifically this solution worked for me. Tested on M2.4.3.

private $gallery_rm
 
public function __construct(
 \Magento\Catalog\Model\ResourceModel\Product\Gallery $gallery_rm
) {
 $this->gallery_rm = $gallery_rm;
}
public function removeImagesFromProduct($product_object) {
 // get all images from product object
 $media_gallery_entries = $product_object->getMediaGalleryEntries();
 foreach($media_gallery_entries as $product_img) {
 $this->gallery_rm->deleteGallery($product_img->getId());
 }
}
answered Mar 30, 2023 at 20:24
2
  • 1
    You saved my day. Many thanks. By doing so, you avoided having to save the entire product, which takes a lot of time Commented Jan 26, 2024 at 16:03
  • @Bafi you're welcome. I'm glad it helped. Commented Jan 31, 2024 at 21:31
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

answered Jul 21, 2019 at 8:53
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";
 
 ?>
answered Jul 13, 2021 at 12:21
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';
 }
 
 ?>
answered Jul 13, 2021 at 12:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.