There are many modules and scripts to delete unused product images in Magento 2.

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.

Now we will go through how to 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. 
    1. 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

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 function does not work here