A safe way to delete product images without a module.  We show two tested ways to delete unwanted images.  However, sometimes trying to keep away from installing new modules is not a bad idea.  Every module introduces a certain risk and requires backup before you attempt to install it.

The first thing we show here is how to find images bigger than 1.2 MB - since most sites do not want those:

find ./pub -name "*.png" -size +1500000c

find ./pub -name "*.jpg" -size +1500000c

Or directly delete the found files:

find ./pub -name "*.png" -size +1500000c -exec rm {} +

Every product image in Magento 2 is stored in two places

  1. pub/media/catalog/product/7/E/7E.jpeg
  2. pub/media/catalog/product/cache/da2041138508c9bfa03804ab5113dbd2/7/E/7E.jpeg

I.  This is how to safely delete unnecessary images:

  1. Export all products.  System -> Export.  Select products from the drop down.  Do not select any fields and just press Continue.
  2. Make a backup of the files and DB
  3. Test the products table that we just exported.  Go to: System -> Import. Select Products, Add/Update. Select field enclosure. Select the file you just downloaded and press Check Data ( Do not proceed to actual import ).
  4. Move images -> pub/media/catalog/product folder to /var/importexport.  At this point the product images will be gone from the site
  5. Now if you have many products it is a good idea to split the CSV file in few.  We split the file in 500 products and worked fine.  
  6. Delete entries from Table `catalog_product_entity_media_gallery` that do not have a corresponding entry in catalog_product_entity_varchar. 

    DELETE FROM `catalog_product_entity_media_gallery` WHERE value NOT IN (SELECT b.value FROM `catalog_product_entity_varchar` b WHERE b.value IS NOT NULL

  7. Once again Select System -> Import.  Select Products, Add/Update.  Select field enclosure. Select the file you just downloaded.  In Images File Directory write the path to the moved images folder var/importexport/product
  8. Run command

    bin/magento catalog:images:resize

A quick summary of what the above has achieved.  We have deleted all images and re-imported only the ones being used.  Straight forward operation that could save a lot of GigaBytes of useless images.  

A couple of SQL statements that might be usefull in the process:

SELECT * FROM `catalog_product_entity_media_gallery` a WHERE a.value NOT IN (SELECT b.value FROM `catalog_product_entity_varchar` b WHERE b.value IS NOT NULL)

SELECT COUNT(DISTINCT value_id) FROM `catalog_product_entity_varchar` WHERE value LIKE '%png’


II.  Another way to delete unused images is using a module.  Here is one that you can use.  It is not risk free, so do a backup first


Commands to use:

bin/magento eav:media:remove-unused --dry-run

bin/magento eav:media:remove-unused

bin/magento eav:attributes:remove-unused 

The dry-run option does not work for the eav attributes ( the last command above ).  It is used to remove all attributes