how do i programaticly delete duplicate images? in magento - image

I manage a big web store with alot of products, and some of the products weren't correctly imported and the images got duplicated.
the products just have 2 of the same images.
i know that you can delete them by hand but that would take up all my life of time.
i have searched the internet for some of the codes that can do it but they dont work for me.
is there anybody who know a solution for this?
I have tried to examine the codes that i got from the internet but i really can make them work.
this is one of the solutions that didn't work for me:
http://dltr.org/blog/magento/556/Magento-product-images-duplicate-issue-with-CSV-product-importer
i have tried to test this query in the sql database but that does not give any result:
SELECT * FROM `catalog_product_entity_media_gallery` WHERE value_id != value_id AND value=value

Here is a little script to find and delete all duplicate images in Magento.
//Mage::App(‘default’);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
error_reporting(E_ALL | E_STRICT);
Mage::setIsDeveloperMode(true);
ini_set(‘display_errors’, 1);
ob_implicit_flush (1);
$mediaApi = Mage::getModel(“catalog/product_attribute_media_api”);
$_products = Mage::getModel(‘catalog/product’)->getCollection();
$i =0;
$total = count($_products);
$count = 0;
foreach($_products as $_prod)
{
$_product = Mage::getModel(‘catalog/product’)->load($_prod->getId());
$_md5_values = array();
//protect base image
$base_image = $_product->getImage();
if($base_image != ‘no_selection’)
{
$filepath = Mage::getBaseDir(‘media’) .’/catalog/product’ . $base_image ;
if(file_exists($filepath))
$_md5_values[] = md5(file_get_contents($filepath));
}
$i ++;
echo “\r\n processing product $i of $total “;
// Loop through product images
$_images = $_product->getMediaGalleryImages();
if($_images)
{
foreach($_images as $_image)
{
//protected base image
if($_image->getFile() == $base_image)
continue;
$filepath = Mage::getBaseDir(‘media’) .’/catalog/product’ . $_image->getFile();
if(file_exists($filepath))
$md5 = md5(file_get_contents($filepath));
else
continue;
if( in_array( $md5, $_md5_values ))
{
$mediaApi->remove($_product->getId(), $_image->getFile());
echo “\r\n removed duplicate image from “.$_product->getSku();
$count++;
}
else
{
$_md5_values[] = $md5;
}
}
}
}
http://www.aadil.co/how-to-delete-duplicate-product-images-in-magento/

Below is a snippet I have used earlier, this works like a charm
Actual link : http://blueclawecommerce.co.uk/blog/removing-duplicate-product-images-in-magento/
include('app/Mage.php'); 
//Mage::App('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
error_reporting(E_ALL | E_STRICT);
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ob_implicit_flush (1);
 
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$_products = Mage::getModel('catalog/product')->getCollection();
$i =0;
$total = count($_products);
$count = 0;
foreach($_products as $_prod)
{
    $_product = Mage::getModel('catalog/product')->load($_prod->getId());
    $_md5_values = array();
     
    //protected base image
    $base_image = $_product->getImage();
    if($base_image != 'no_selection')
    {
        $filepath =  Mage::getBaseDir('media') .'/catalog/product' . $base_image  ;
        if(file_exists($filepath))
            $_md5_values[] = md5(file_get_contents($filepath));
    }
             
     
    $i ++;
    echo "\r\n processing product $i of $total ";
 
    // Loop through product images
    $_images = $_product->getMediaGalleryImages();
    if($_images){
        foreach($_images as $_image){
            //protected base image
            if($_image->getFile() == $base_image)
                continue;
             
            $filepath =  Mage::getBaseDir('media') .'/catalog/product' . $_image->getFile()  ;
            if(file_exists($filepath))
                $md5 = md5(file_get_contents($filepath));
            else
                continue;
             
 
            if(in_array($md5, $_md5_values))
            {
                $mediaApi->remove($_product->getId(),  $_image->getFile());
                echo "\r\n removed duplicate image from ".$_product->getSku();
                $count++;
            } else {
                $_md5_values[] = $md5;
            }   
 
        }
    }
     
}
echo "\r\n\r\n finished removed $count duplicated images";

I have a solution that you can adapt.
To delete them physically you need to run it with an import to be sure to have the good images at the end.
$_images = $product->getMediaGalleryImages();
if($_images){
foreach($_images as $_image){
$filepath = Mage::getBaseDir('media') .'/catalog/product' . $_image->getFile() ;
check if the both images (the one to import and the one that is present on the server) have the same size else
}
}
To delete from the database the image linked to a product (still during an import).
$query = "select value_id from catalog_product_entity_media_gallery where entity_id = ?";
$st = $cnx->prepare($query);
$st->execute(array($productId));
$row = $st->fetch();
while ($row !== false) {
$values2delete[] = $row['value_id'];
$row = $st->fetch();
}
$query = "delete from catalog_product_entity_media_gallery where value_id IN (". implode(',',$values2delete).")";
$st = $cnx->prepare($query);
$st->execute();
I do not use this two things in the same import so you need to marry them together. You can also fill the values2delete array during the check of the bad files.
I hope it helps

Related

How delete not selection Base image, Small etc

$product1 = Mage::getModel('catalog/product')->loadByAttribute('sku', 'FN244403');
$product2 = Mage::getModel('catalog/product')->loadByAttribute('sku', 'FN229437');
$product1ID = $product1->getId();
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = "SELECT * FROM `catalog_product_entity_media_gallery` WHERE `entity_id` = '$product1ID'
LIMIT 1";
$rows = $connection->fetchAll($sql);
echo $path = $rows[0]['value'];
echo "Edited sku is ".$product1->getSku()." ".$product1->getImage()." ".$product1-
>getThumbnail()." ".$product2->getImage();
echo " asdasd ".Mage::getBaseDir('media') . DS . 'catalog/product' .trim($rows[0]['value']);
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$product1->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'catalog/product' .trim
($rows[0]['value']), array('image', 'small_image', 'thumbnail'), false, false);
$product1->save();
I am adding product images such as Small image, Base image, Thumbnail. How I can delete second lost image which not selected as Small image, Base image, Thumbnail?
Take a look # Magento programmatically remove product images
$collection = Mage::getModel('catalog/product')->getCollection();
foreach($collection as $product){
if ($product->getId()){
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
foreach($items as $item){
view elements of $item array
print_r($item);
if($item[] not check ){
$mediaApi->remove($product->getId(), $item['file']);
}
}
}
}

How to create custom script for import products in magento

I am working on magento 1.8 version.
I need to create custom script or extenson for import product from my custom csv file which have some different fields.
Any help would be much appriciated.
Thanks
Best way is to use OS Magmi, is much more faster than script an is simple to configure and periodical run.
http://sourceforge.net/projects/magmi/
You can also create a script which can you run.
you need to get data from csv file to memory
2 convert them to array
3 list array for each product
4 in foreach loop save or update product.
Some basic script:
<?php
$max_i = 20000; // maximal ammount
chdir(dirname(__FILE__)); /
//error_reporting(E_ALL | E_STRICT);
//ini_set("display_errors", 1);
ini_set("memory_limit","1024M");
ini_set('max_execution_time', 3600000);
date_default_timezone_set('Europe/Prague');
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
//////// SKU from CSV
$csv = file_get_contents ('yourcsvfile.csv');
function parse_csv ($csv_string, $delimiter = ";", $skip_empty_lines = true, $trim_fields = true)
{
$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
$enc = preg_replace_callback(
'/"(.*?)"/s',
function ($field) {
return urlencode(utf8_encode($field[1]));
},
$enc
);
$lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
return array_map(
function ($line) use ($delimiter, $trim_fields) {
$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
},
$fields
);
},
$lines
);
}
// list to array
$vystup = parse_csv($csv);
$seznamsku = array();
foreach ($vystup as $sku) {
array_push($seznamsku, $sku[0]);
unset($seznamsku[0]);
$seznamskufin = array_filter($seznamsku, 'strlen');
};
require("../../app/Mage.php");
echo "START ".date('h:i:s')."\n\n";
Mage::init();
// Set an Admin Session
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(1);
$session = Mage::getSingleton('admin/session');
$session->setUser($userModel);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
$pocet = 1;
foreach ($seznamskufin as $item) {
echo "\n number(".$pocet.")..sku(".$item.")..";
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$item);
if(is_object($product)) { //if is product exist in Magento
if (empty($product->getShortDescription())) { // if is value empty
$product->setShortDescription($ZboziDetail['info']); // write to magento
echo "..(importing)..";
}
else
{
echo "..(skipped).."; // exists
};
$product->save(); // save to magento
echo "..saved";
} else { echo ".(skiped)"; };
unset($item);
unset($product);
unset($ZboziDetail);
unset($product_imageUrl);
unset($newimage);
unset($e);
$pocet++;
};
$time_end = microtime_float();
$time = $time_end - $time_start;
echo " \n\n All done in ".$time." seconds.";
$logfile = fopen('log.txt', 'a');
fwrite($logfile, $seznamskufin);
fclose($logfile);
unset($response);
unset($vystup);
unset($seznamsku);
unset($seznamskufin);
?>
I think the easiest and safest way is to create a simple script (outside Magento) that transforms your csv to the csv structure used for import in System->Import/Export->Import.
TO see the format of the csv you need go to System->Import/Export->Export and export your current products.

Get product image url in prestashop 1.5.4

I uploaded my product images as follow: an image with 1234 id will be uploaded in img/p/1/2/3/4/1234-large_default.jpg when i viewed the product information related to the image, a default file (product image unavailable) is displayed.
my code for adding images to database
$res = "insert into "._DB_PREFIX_."image (`id_product`,`position`,`cover`) values
(".$id_product.",1, 1)";
if (!Db::getInstance()->execute($res))
die('Erreur etc.');
$id_image = Db::getInstance()->Insert_ID();
$res = "insert into "._DB_PREFIX_."image_lang (`id_image`,`id_lang`) values (".$id_image.", 1)";
if (!Db::getInstance()->execute($res))
die('Erreur etc.');
$res = "insert into "._DB_PREFIX_."image_lang (`id_image`,`id_lang`) values (".$id_image.", 2)";
if (!Db::getInstance()->execute($res))
die('Erreur etc.');
$stmt = "insert into "._DB_PREFIX_."image_shop(`id_image`,`id_shop`,`cover`) values (".$id_image.",1,1)";
$folders = str_split($id_image);
$i = 0;
$base_uri ='var/www/autospareparts.se.com/img/p/';
$folders = str_split($id_image);
$i = 0;
$base_uri ='/var/www/autospareparts.se.com/img/p/';
while( $i <sizeof($folders) )
{
$base_uri .= $folders[$i].'/';
if($i==(sizeof($folders) -1))
{if(!is_dir( $base_uri))
if(!mkdir($base_uri, 0777, true))
die('Echec lors de la création des répertoires...');
download_remote_file('http://pic1.aldoc.eu/PicData /'.$pic,$base_uri.$id_image.'large_default.jpg' );
}
//fin else
$i++;
}
I showed the code of mytheme/product.tpl i found
$link->getImageLink($product->link_rewrite, $cover.id_image, 'large_default')
which return img/p/fr-default-large_default.jpg
Can you tell me what's wrong?
Thanks
$image = new Image($id_image);
$image_url = _PS_BASE_URL_._THEME_PROD_DIR_.$image->getExistingImgPath().".jpg";
OR if images got path like img/p/1/2/3/4-1234.jpg:
function imgurl($img_id){
$ids="".$img_id;
$result="";
for ($i=0;$i<strlen($ids);$i++){
$result.=$ids[$i]."/";
}
$result.=$img_id;
return $result;
}

Daily Inventory Update through remote FTP file

It’s been 2 days and I came across many tutorials, videos, extension which explains how to do daily updates on my products but none of them seem to work.
I have a website which has around 3,000 products with attributes and all. My supplier updates the inventory file on daily basis and the updated inventory file is kept on a remote ftp to which I have access to.
What I need is the following:
Daily inventory update which will include, prices, quantity, etc
Remove items which has quantity 0
Add new items as per the updated inventory file
I am sure someone out there has answer to my questions. So please get back to me asap.
Fisrt, by "Remove items which has quantity 0", I think you mean to set products as "out of stock" when the inventory is decreased to 0. This is handled automatically by Magento after you update the inventory.
The built-in import/export function should fulfill your requirements.
Some more tutorials if you don't mind:
Tutorial: Using Magento’s Import/Export Profiles
How to add/edit/remove products using the import/export tool
Here, I will share just inventory update ( but this is not good way ). You should create "tab delimited" file as follows :
SKU QTY
978 34
633 0
Then you can create cron job to run this script.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
set_time_limit(0);
ini_set('memory_limit','1024M');
include('app/Mage.php');
Mage::App('default');
//get magento db connection for query
$db_query = Mage::getSingleton('core/resource')->getConnection('core_read');
//get magento db connection for update, add, delete sql statements
$db_update = Mage::getSingleton('core/resource')->getConnection('core_write');
//mail receipent
$to = 'youremail#yoursite.com';
if ($handle = opendir('./var/export'))
{
while (false !== ($file = readdir($handle)))
{
$sku_success = '';
if ($file != '.' && $file != '..')
{
$filename = './var/export/'.$file;
$handle_file = fopen($filename,'r');
$counter = 1;
while (($data = fgetcsv($handle_file, 1000, '\t'))!== FALSE) //read tab delimited
{
if($counter!=1)
{
$sku= $data[0];
$qty = $data[1];
$exists = $db_query->query("SELECT COUNT(sku) cnt FROM catalog_product_entity WHERE sku = '$sku' LIMIT 1");
$found = (($exists->fetchObject()->cnt) > 0) ? true : false;
if ($found == true) //product found, update
{
$entity_id = getEntityIdBySku($db_query, $sku);
updateStockQty ($db_update, $entity_id, $qty);
echo 'product $sku inventory updated?';
$sku_success.= $sku;
} else {
//sku not found, notify by email
$body = "SKU#:".$sku." of ".$file." with a qty of ".$qty." was not found in the the inventory";
sendMsg("SKU#:".$sku." not found!",$to,$body);
}
}
$counter++;
}
fclose($handle_file);
$body = "<strong>SKU?S IMPORTED</strong>".$sku_success."<br/>";
sendMsg($file." successfully imported!",$to,$body);
}
}
closedir($handle);
}
function getEntityIdBySku($db_connection, $sku) //get entity id by its sku
{
$entity_row = $db_connection->query("SELECT entity_id FROM catalog_product_entity p_e WHERE p_e.sku = '$sku'")->fetchObject();
$entity_id = $entity_row->entity_id;
return $entity_id;
}
function updateStockQty($db_connection, $entity_id, $qty) //updates the stock quantity
{
$db_connection->query("UPDATE cataloginventory_stock_item s_i, cataloginventory_stock_status s_s
SET s_i.qty = '$qty', s_i.is_in_stock = IF('$qty'>0, 1,0),
s_s.qty = '$qty', s_s.stock_status = IF('$qty'>0, 1,0)
WHERE s_i.product_id = '$entity_id' AND s_i.product_id = s_s.product_id ");
}
function sendMsg($subject, $to, $body)//sends email
{
$headers = 'MIME-Version: 1.0' . '\n';
$headers .= 'Content-type: text/html; charset=iso-8859-1'. '\n';
$headers .= 'To: '.$to. '\n';
$headers .= 'From: webmaster#yoursite.com'. '\n';
if (mail($to, $subject, $body,$headers))
{
echo('Message sent!');
} else {
echo('Message failed.');
}
}
?>
The script by courtesy of the Deepcodeonline

Magento programmatically remove product images

This must be a such a simple programming task that I absolutely cannot find any information about it on the net. Basically, I'm trying to DELETE product images. I want to delete all images from a product's media gallery. Can I do this without wading through a million lines of code for such a simple task?
Please note that I've already tried this:
$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes['media_gallery'])) {
$gallery = $attributes['media_gallery'];
$galleryData = $product->getMediaGallery();//this returns NULL
foreach($galleryData['images'] as $image){
if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
}
}
}
This absolutely does not work. I'm trying to delete images during an import so that I do not keep accruing duplicates. Any help would be greatly appreciated.
Okay, this is how I finally fixed my problem.
if ($product->getId()){
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
foreach($items as $item)
$mediaApi->remove($product->getId(), $item['file']);
}
This is the link that finally set my head straight: http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product_attribute_media
Too bad it's not as simple as $product->getImages(), eh?
In Magento 1.7.0.2 I use this code for remove all images from a product gallery:
//deleting
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
if ($gallery->getBackend()->getImage($product, $item['file'])) {
$gallery->getBackend()->removeImage($product, $item['file']);
}
}
$product->save();
With code from Davids Tay answer, I got the error:
Fatal error: Uncaught exception ‘Mage_Eav_Model_Entity_Attribute_Exception’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (base_xxx.catalog_product_entity_media_gallery_value, CONSTRAINT FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID FOREIGN KEY (value_id) REFERENCES `catalog_prod)’
To remove all images from a product gallery:
$product = Mage::getModel('catalog/product')->load($id);
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($entityTypeId, 'media_gallery');
$gallery = $product->getMediaGalleryImages();
foreach ($gallery as $image)
$mediaGalleryAttribute->getBackend()->removeImage($product, $image->getFile());
$product->save();
During deleting of images I found one interesting thing. When you try this code:
$galleryData = $product->getMediaGallery(); //this returns NULL
Media gallery object depends on how your product was created, if:
$product = Mage::getModel('catalog/product')->loadByAttr('sku', $sku);
then media gallery will be empty, if:
$product = Mage::getModel('catalog/product')->load($id);
then media gallery is object and you can use this object to delete images from db.
To delete images from file system you have to add such code:
#unlink(Mage::getBaseDir('media') . '\catalog\product\' . $image['file']);
but if you want to change image and name it like previous image (image1.png replace with image1.png) in this case you will have browser caching issue.
Also you can try to load media gallery for product:
$product->getResource()->getAttribute('media_gallery')->getBackend()->afterLoad($product);
This is the code I finally decided to use for this task.
protected function _removeMediaGalleryImages(Mage_Catalog_Model_Product $product)
{
$mediaGalleryData = $product->getMediaGallery();
if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {
return;
}
$toDelete = array();
foreach ($mediaGalleryData['images'] as $image) {
$toDelete[] = $image['value_id'];
}
Mage::getResourceModel('catalog/product_attribute_backend_media')->deleteGallery($toDelete);
}
Hopefully this answer isn't unwelcome, as it's technically not a solution achieved via Magento programming as you ask, but I have successfully purged all gallery images myself for the same purpose simply by truncating the relevant tables in Magento 1.4.2.0 (I believe it's the same table structure in 1.5 as well).
TRUNCATE TABLE `catalog_product_entity_media_gallery`
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`
Then follow up by removing all the image files within the /media/catalog/product directory.
I did look for a way to do this programmatically myself, but found this much more efficient and have experienced no negative side effects.
Just use this code to create .php file and place it to root folder of magento.
<?php
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
//->addAttributeToFilter('entity_id', array('gt' => 14000));
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
foreach($products as $product) {
$prodID = $product->getId();
$_product = Mage::getModel('catalog/product')->load($prodID);
$items = $mediaApi->items($_product->getId());
foreach($items as $item) {
$mediaApi->remove($_product->getId(), $item['file']);
}
}
?>
What About this
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
if ($gallery->getBackend()->getImage($product, $item['file'])) {
$gallery->getBackend()->removeImage($product, $item['file']);
}
}
$product->save();
Fastest way to remove image,then follow below steps:
delete all records from
catalog_product_entity_media_gallery
catalog_product_entity_media_gallery_value'
table because magento is save all product image data at those table.
Then index from Index management from admin for set image black.
Then remove image from dir then goto Your magento dir at media/catalog/product and from this folder delete all file.
Another Process:
Andy Simpson,you need a script which is delete all product from your system which will delete from DB and file system.
Step1: Create a php at root direct of magento system which include Mage.php at first code.
require_once "YOURMAGENTODIR/app/Mage.php";
umask(0);
Step2: set current store is admin and set Developer mode
Mage::app('admin');
Mage::setIsDeveloperMode(true);
Step3: Get Product Collection and create a loop for get one product by one by one
$productCollection=Mage::getResourceModel('catalog/product_collection');
Step4: fetch product image by one and remove image one using below code:
$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
FULL CODE:
<?php
require_once "YOURMAGENTODIR/app/Mage.php";
umask(0);
Mage::app('admin');
Mage::setIsDeveloperMode(true);
$productCollection=Mage::getResourceModel('catalog/product_collection');
foreach($productCollection as $product){
echo $product->getId();
echo "<br/>";
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
echo "<br/>";
$MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
echo "<pre>";
print_r($MediaGallery);
echo "</pre>";
foreach($MediaGallery as $eachImge){
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
$MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
$DirImagePath=str_replace("/",DS,$eachImge['file']);
$DirImagePath=$DirImagePath;
// remove file from Dir
$io = new Varien_Io_File();
$io->rm($MediaCatalogDir.$DirImagePath);
$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
}
}
If you want to remove more products like 1000 or 5000 then use bottom one with direct query.
Before try this one take backup of your database
<?php
require_once 'app/Mage.php';
umask(0);
Mage::app();
set_time_limit(0);
ini_set('display_error','1');
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_write');
$id = 101;
$product = Mage::getModel('catalog/product')->load($id);
$q = "DELETE FROM `catalog_product_entity_media_gallery` where entity_id = '".$product->getId()."'";
$connection->query($q);
?>
Accessing the Database for such things is a bad idea.
You can delete images ( or reorder them by changing the 'position' value ) using the following snippet in a custom module ( for the sake of simplicity i'm using ObjectManager, but you should place ProductFactory and ProductRepositoryInterface in the constructor )
$objectManager = ObjectManager::getInstance();
//Get ProductFactory in order to instatiate the Product Object
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
//We have to use ProductRepositoryInterface in order to save the changes bellow to the product
$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
//Load a Product by ID in this case 1
$product = $productFactory->create()->load(1);
//Gets an array containing arrays representing each image in the gallery
$mediaGalleryEntries = $product->getMediaGalleryEntries();
//Here we delete every image, you can use conditions in foreach
foreach ($mediaGalleryEntries as $key => $imageEntry) {
unset($mediaGalleryEntries[$key]);
}
//Finally set the altered entries and save using productRepository
$product->setMediaGalleryEntries($mediaGalleryEntries);
$productRepository->save($product);
The code above tested in Magento 2.3 and it also removes images from the filesystem. You can use it to either delete or alter an entry ( change position, image roles etc )
To view each imageEntry you can access its data using $imageEntry->getData()
I had to do something similar not too long ago - needed to replace all product images during an import.
This link helped a lot: http://www.sharpdotinc.com/mdost/2010/03/02/magento-import-multiple-images-or-remove-images-durring-batch-import/
Hopefully it will give you a nudge in the right direction.
DELETE FROM catalog_product_entity_media_gallery WHERE value_id NOT IN (SELECT * FROM (SELECT MIN(value_id) FROM `catalog_product_entity_media_gallery` GROUP BY LEFT(value,17), entity_id having count(*) > 1) x)
why 17 ?
The expamle you have duplicate like this:
/0/0/000116810609_1.jpg
/0/0/000116810609_2.jpg
/0/0/000116810609_3.jpg
/0/0/000116810609_4.jpg
LEFT(value,17)
/0/0/000116810609
/0/0/000116810609
/0/0/000116810609
/0/0/000116810609
No they are duplicates ;)
Place the below script in magento root and execute
<?php
require_once("app/Mage.php");
umask(0);
Mage::app();
$ob = new Clean();
$ob->removemedia();
Class Clean {
function removemedia() {
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $read->select()
->from('catalog_product_entity_media_gallery', '*')
->group(array('value_id'));
$flushImages = $read->fetchAll($select);
echo count($flushImages);
$array = array();
foreach ($flushImages as $item1) {
$array[] = $item1['value'];
}
$valores = $array;
$pepe = 'media' . DS . 'catalog' . DS . 'product';
$leer = $this->listDirectories($pepe);
foreach ($leer as $item) {
try {
$item = strtr($item, '\\', '/');
if (!in_array($item, $valores)) {
$valdir[]['filename'] = $item;
unlink('media/catalog/product' . $item);
}
} catch (Zend_Db_Exception $e) {
} catch (Exception $e) {
//Mage::log($e->getMessage());
}
}
}
function listDirectories($path) {
if (is_dir($path)) {
if ($dir = opendir($path)) {
while (($entry = readdir($dir)) !== false) {
if (preg_match('/^\./', $entry) != 1) {
if (is_dir($path . DS . $entry) && !in_array($entry, array('cache', 'watermark'))) {
$this->listDirectories($path . DS . $entry);
} elseif (!in_array($entry, array('cache', 'watermark')) && (strpos($entry, '.') != 0)) {
$this->result[] = substr($path . DS . $entry, 21);
}
}
}
closedir($dir);
}
}
return $this->result;
}
}

Resources