Magento 2 delete unused product images - Cleanup image files
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.
Every product image in Magento 2 is stored in two places:
I. This is how to safely delete unnecessary images:
- Export all products. System -> Export. Select products from the drop down. Do not select any fields and just press Continue.
- Make a backup of the files and DB
- 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 ).
- Move images -> pub/media/catalog/product folder to /var/importexport. At this point the product images will be gone from the site
- 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.
- 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
- 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
- Run command
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
The dry-run option does not work for the eav attributes ( the last command above ). It is used to remove all attributes