Magento: Import Multiple Images or Remove Images durring Batch Import

This article will detail how to adjust the Magento Batch Import (Dataflow) to allow uploading multiple gallery images, and also how to add a way to remove all images during Import/Update.

These are the accompaning files: (Please reference this file if you have any quetion about the code examples below. The WYSIWYG editor was messing things up. mainly “&’s” and “empty()’s” )
1. Full Code Example

First we are going to have to modify the the adapter used to save/update products during the import process. The file used is located here: “/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php“. Since we are going to be modifying this file we should extend it so we don’t change any core files. There are plenty of articles that detail how to extend/customize Magento files so I will not go into it.

First lets tackle adding multiple gallery images. These are images that appear on the products detail page below the main image. We will be making all our edits in the Product.php file mentioned in the previous paragraph. Find the SaveRow method. In this method find the code where Magento saves the products images(should be similar to the following code and around line 630).
[sourcecode language=’php’] $imageData = array();
foreach ($this->_imageFields as $field) {
if (!empty($importData[$field]) && $importData[$field] != ‘no_selection’) {
if (!isset($imageData[$importData[$field]])) {
$imageData[$importData[$field]] = array();
}
$imageData[$importData[$field]][] = $field;
}
}

foreach ($imageData as $file => $fields) {
try {
$product->addImageToMediaGallery(Mage::getBaseDir(‘media’) . DS . ‘import’ . $file, $fields);
}
catch (Exception $e) {}
}
[/sourcecode]

First thing we will do is change the addImageToMediaGallery so that when it saves the image it is not excluded(saves you from having to re-edit the products after import to make the images appear.).
[sourcecode language=’php’]

foreach ($imageData as $file => $fields) {
try {
// changed to not mark imported images as ‘excluded’ – see http://www.magentocommerce.com/boards/viewthread/6971/P15/ and http://www.magentocommerce.com/boards/viewthread/40007/
//$product->addImageToMediaGallery(Mage::getBaseDir(‘media’) . DS . ‘import’ . $file, $fields);
$product->addImageToMediaGallery(Mage::getBaseDir(‘media’) . DS . ‘import’ . $file, $fields, false, false);
}
catch (Exception $e) {}
}
[/sourcecode]

Now we can add the code to import multiple gallery images. Just below the code above add this new code:
[sourcecode language=’php’] //Now add each gallery image.
if (!empty($importData[‘gallimg’])) {
//$importData[‘gallimg’] should be a list of images to import seperated by “;”
$images = explode(“;”, $importData[‘gallimg’]);
foreach($images as $image){
//Don’t add field for gallimg’s
try {
//made second param null so it is not added as the main image, small or thumb. just added to the gallery
$product->addImageToMediaGallery(Mage::getBaseDir(‘media’) . DS . ‘import’ . trim($image), NULL, false, false);
}
catch (Exception $e) {}

}
}
[/sourcecode] In order to use this new code you need to add a new column to your import spreadsheet. Label the column “gallimg”. This needs to be a list of the images you want to import separated by a “;”.
Now that was not too hard was it?

Now we can address removing images during the import/update process. In order to remove all the images you will need to continue modifying the saveRow method. Add the following code just above the code we previously edited.

[sourcecode language=’php’] //MRD added to remove all images for product before uploading new images
if(isset($importData[‘remove_all_images’]) && $importData[‘remove_all_images’]==”yes” ){
//check if gallery attribute exists then remove all images if it exists
//Get products gallery attribute
$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes[‘media_gallery’])) {
$gallery = $attributes[‘media_gallery’];
//Get the images
$galleryData = $product->getMediaGallery();
foreach($galleryData[‘images’] as $image){
//If image exists
if ($gallery->getBackend()->getImage($product, $image[‘file’])) {
$gallery->getBackend()->removeImage($product, $image[‘file’]);
}
}
}
#$gallery->clearMediaAttribute($product, array(‘image’,’small_image’,’thumbnail’));
}
//END Remove Images
[/sourcecode]

To utilize the code we just created you will need to add the “remove_all_images” column to your spreadsheet and set the value to “yes”.

This was written using Magento version 1.2.1 so your files could be slightly different, but should still work if you follow the instruction. If you have any problems please leave a productive comment and I will see how I can help.

About The Author



47 Comments

James » 23 Mar 2010 » Reply

Hi Mike,
Thanks for sharing this code. It’s made my life much easier. However I’m having a problem with it that I just can’t figure out. The problem is specifically related to the delete images chunk of code.

Your code is in the proper location in my script and I’ve made no modifications to it. I am using a modified import script though, which allows for the uploading of configurable products.

When the delete images column is set to true, everything gets imported but the configurable attribute on my configurable products does not get set. If I set delete_all_images to ‘no’ the problem is resolved.

Looking through your code I can’t figure out why this would be happening, it’s not making any sense to me, and my head is starting to hurt almost as bad as my keyboard it keeps hitting.

If you’ve heard of this issue or have any off-the-top-of-your-head suggestions please share, but please don’t go out of your way.

Thanks,
James

Mike D » 23 Mar 2010 » Reply

Hmm… I am not sure what would be causing the Remove Images functionality to be affecting any other part of the import process. A work around would be to import the images then remove the image fields from the import spreadsheet and re-import the data again. this way you don’t need to use the remove images functionality. I only used it so I did not need to remove the image from the spreadsheet if I adjusted any information and had to re-import it.

optical » 8 Apr 2010 » Reply

Hi Mike,

I could use some help here. I’m trying to make this work and have added your codes into my Product.php but getting this error during import.

Parse error: syntax error, unexpected T_PUBLIC in /home/user/public_html/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php on line 776

my line 776 is this:

public function saveRowSilently(array $importData)

optical » 8 Apr 2010 » Reply

Sorry, I forgot to include my version which is 1.3.2.3

Mike D » 8 Apr 2010 » Reply

It looks like you probably did not close a function above this one. I believe this error is saying that PHP was not expecting a function to be declared. Your Error will be in the code above line 776.

Chris » 13 May 2010 » Reply

I am getting this error in Magento 1.4.0.1

Warning: Invalid argument supplied for foreach() in /home/folder/public_html/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php on line 694

line 694 is in the Remove Image section:
foreach($galleryData[‘images’] as $image){

Any ideas of the source of the problem?

Thanks,

Chris

Mike D » 14 May 2010 » Reply

Try doing a print_($galleryData); and see if $galleryData[‘images’] is in the array. I have not used this on Magento 1.4.x and they might have changed things a little.

Let me know whats in the array and we can proceed from there.

Abi » 15 May 2010 » Reply

Hi Mike,

Thanks for the share, your code helps me fixing this problem of duplicate image (my version is 1.4.0.1).
I have added a little line because magento keeps adding a new picture in the catalog/product folder and change the picture’s name each time you import again the product so you have to remove directly the picture :


if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
unlink (Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $image['file']);
}

Greg » 11 Jun 2010 » Reply

One more thing. Image imports always trip me up by requiring a / before the filename. All you have to do is add the following lines to your code after the try { in code sample number 3. This adds a / to your image file name if it’s not already there.


// if the leading / was forgotten then add it

if (substr($file, 0, 1) '/') {
$file = '/'.$file;
}

This will make the whole foreach loop look like this –


foreach ($imageData as $file => $fields) {
try {
// if the leading / was forgotten then add it
if (substr($file, 0, 1) '/') {
$file = '/'.$file;
}

$product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $file, $fields);
}
catch (Exception $e) {}
}

Also – remember that the images you want to import go into the media/import directory not the var/import

Cheers
Greg

Qasim » 30 Jun 2010 » Reply

Hi Mike,

Thanks for your good job.
I am using magento 1.4.1.0. When I import data from csv file by your code, images imported successfully but images are not setting as “thumbnail”, “image” or “small_image”.
can you tell me why? I have searched to resolve this problem but failed.

Can you resolve this problem?

Regards,

Qasim

Mike D » 30 Jun 2010 » Reply

@Qasim – Hey It has been a while since I have used this script. In the cvs file you should have images in each column that you want to set(ex: image, thumbnail, …).

Create a product using Magento with images then export this product(this will give you a base csv file to work with) and make sure that your fields are named the same when importing.

I have not tested this in Newer versions of Magento, but I don’t see why any thing related to this would have changed.

RI GUCCI » 4 Jul 2010 » Reply

I am use 1.4.1.0 now,
when i upload batch as before 1.4.0.1,
it is show error now:
———————————
Starting profile execution, please wait…
Warning: Please do not close the window during importing/exporting data
Starting Mage_Dataflow_Model_Convert_Parser_Csv :: parse
Method “parse” not defined in adapter catalog/convert_adapter_product.
Please wait while the indexes are being refreshed.
Finished profile execution.
———————————
Any good idea?

    Mike D » 4 Jul 2010 » Reply

    The only thing I can think of is that you need to re-index everything, then try again.

Laura » 8 Jul 2010 » Reply

Hello,

I am very excited about this code, but when I perform the import I am getting this error:

Notice: Undefined property: Mage_Catalog_Model_Convert_Adapter_Product::$_inventorySimpleFields in /home/wwwfore7/public_html/friend/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php on line 616

Any ideas?

Thanks again.

Laura » 8 Jul 2010 » Reply

Also, if i let the import run with the notice, I get this at the very end about 10 times:

Parse error: syntax error, unexpected T_IF, expecting T_FUNCTION in /home/wwwfore7/public_html/friend/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php on line 664

Mike D » 12 Jul 2010 » Reply

@Laura:
RE – Mage_Catalog_Model_Convert_Adapter_Product::$_inventorySimpleFields:
1. Did you edit the core file or override the core file?
2. What version are you using?
3. Does the
3. Please post a line or two above and below the line the error was on.

RE – Parse error: syntax error, unexpected T_IF, expecting T_FUNCTION:
This sounds like your braces are not closed right. Check your code.

Muzafar » 14 Jul 2010 » Reply

hi,

can i import product from RSS FEED of other websites ..?

Mike D » 14 Jul 2010 » Reply

I am not sure.I have never tried it. I would assume that if the feed has all the required data and you had the attributes and attribute set already set up you could.

Chris » 14 Jul 2010 » Reply

I just wanted to follow up a bit from my first post. Here is my first post:

I am getting this error in Magento 1.4.0.1

Warning: Invalid argument supplied for foreach() in /home/folder/public_html/app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php on line 694

line 694 is in the Remove Image section:
foreach($galleryData[‘images’] as $image){

Well I found out that you cannot have the “remove_all_images” column in your first import, you must have images for your products first.

Also, I found that instead of editing the core file, it is a lot safer to go ahead and make a local file ( /public_html/app/code/local/Mage/Catalog/Model/Convert/Adapter/Product.php)Then if it doesn’t work just delete it.

Thanks again Mike…I seemed to have ironed out all my problems.

Chris

eropatra » 19 Aug 2010 » Reply

Thanks!!! very good!!!!!

dmagento » 21 Nov 2010 » Reply

Hi,

You code really help me to delete gallery images. Thanks!

In addition, i also need to delete base image because if i reimport, same image get saved in different image name which i dont want.

I appreciate you help!

Deepak

djowie » 11 Apr 2011 » Reply

any solution for magento 1.5.0.1?

    Mike D » 11 Apr 2011 » Reply

    In Version 1.5+ I believe that they have changed how the images are added to the products. I have not really looked into it, so I don’t have a solution. If/When I work with version 1.5+ I will update this post to show how to do it.

Oleg » 10 May 2011 » Reply

Mike D,
I’m really like your hack for images bulk upload!
Hope to see 1.5 version soon! :)

djowie » 2 Jun 2011 » Reply

pff still no 1.5 solution for this issue? anyone?

Karr » 23 Aug 2011 » Reply

Please help as I don’t know what else to do here. None of the above solutions helped me bulk remove assigned images from products (Magento 1.5) . The code to ‘remove images’ during import removes assignment but the images still show up. I need some code that would delete those images from the product, like they were never there. If I delete images from server, I get bunch of no-image images.

Mike D » 23 Aug 2011 » Reply

@Karr: add a die() to into the if statement for “remove_all_images” and make sure that it is getting there. You should see an error thrown during the import when it reaches the die().
If you are getting inside the if statement then Magento may have changed how the “media_gallery” attribute adds or removes images from the products.

Let me know if you are getting inside the if statement.

Karr » 23 Aug 2011 » Reply

Thank you for prompt respond, Mike. I am not that fluent with php but hopefully you can help.

I am editing core product.php file (just like it is described in the beginning of this thread)

The code is:

//MRD added to remove all images for product before uploading new images
if(isset($importData['remove_all_images']) && $importData['remove_all_images']=="yes" ){
//check if gallery attribute exists then remove all images if it exists
//Get products gallery attribute
$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes['media_gallery'])) {
$gallery = $attributes['media_gallery'];
//Get the images
$galleryData = $product->getMediaGallery();
foreach($galleryData['images'] as $image){
//If image exists

if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
}
}
}
$gallery->clearMediaAttribute($product, array('image','small_image','thumbnail'));
}

//END Remove Images

Where do I add ‘die’ function? Please advise and thanks again!

Mike D » 23 Aug 2011 » Reply

add it just above this line

//check if gallery attribute exists then remove all images if it exists

Karr » 23 Aug 2011 » Reply

Mike,

I am getting this error:

Parse error: syntax error, unexpected T_VARIABLE

on this line:

$attributes = $product->getTypeInstance()->getSetAttributes();

Mike D » 23 Aug 2011 » Reply

you probably for got the “;” after die

Should be: die();

Karr » 23 Aug 2011 » Reply

Well, the error went away but adding ‘die’ function didn’t remove images from product. Images got un-marked but still present (associated). Is there any extra solution you could think of?

Mike D » 23 Aug 2011 » Reply

adding the die was not to remove the images, it was to see if you were actually getting into the if statement that removes the images.

If you did not see any red lines when running the import then you did not get into the if statement, thus no images would be removed.

what value do you have in the “remove_all_images” field in you spreadsheet?

Karr » 23 Aug 2011 » Reply

remove_all_images value is ‘yes’

Mike D » 23 Aug 2011 » Reply

Add this line

print_r($importData['remove_all_images']);die("Remove Images Value");

just above this line

if(isset($importData['remove_all_images']) && $importData['remove_all_images']=="yes" ){

ANd let me know what it displayes when you run the import. It should be displayed in a red errors box

Karr » 23 Aug 2011 » Reply

Nope, everything went the way it would if everything was fine. No errors. What does it mean?

Karr » 23 Aug 2011 » Reply

I moved the code lower and It just displayed

yesRemove Images Value in red error box!

Mike D » 23 Aug 2011 » Reply

Seems like the file is not being used.

Just to make sure we are on the same page,
1. please post a few lines of the code you changed just changed, so I can make sure that you changed it in the right spot.

2. IN magento 1.5 there are actually a few spots you can import/export from. Please list exactly where you go to import(in the admin).

Karr » 23 Aug 2011 » Reply

I import via: import/export – dataflow-profiles – import all products

Here is the code (the one that finally gave me red error)

foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
$addedFile = '';
if (isset($importData[$mediaAttributeCode . '_label'])) {
$fileLabel = trim($importData[$mediaAttributeCode . '_label']);
if (isset($importData[$mediaAttributeCode])) {
$keyInAddedFile = array_search($importData[$mediaAttributeCode],
$addedFilesCorrespondence['alreadyAddedFiles']);
if ($keyInAddedFile !== false) {
$addedFile = $addedFilesCorrespondence['alreadyAddedFilesNames'][$keyInAddedFile];
}
}

if (!$addedFile) {
$addedFile = $product->getData($mediaAttributeCode);
}
if ($fileLabel && $addedFile) {
$mediaGalleryBackendModel->updateImage($product, $addedFile, array('label' => $fileLabel));
}
}

//MRD added to remove all images for product before uploading new images
print_r($importData['remove_all_images']);die("Remove Images Value");
if(isset($importData['remove_all_images']) && $importData['remove_all_images']=="yes" ){
die();
//check if gallery attribute exists then remove all images if it exists
//Get products gallery attribute
$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes['media_gallery'])) {
$gallery = $attributes['media_gallery'];
//Get the images
$galleryData = $product->getMediaGallery();
foreach($galleryData['images'] as $image){
//If image exists

if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
}
}
}
$gallery->clearMediaAttribute($product, array('image','small_image','thumbnail'));
}

//END Remove Images
}

$product->setIsMassupdate(true);
$product->setExcludeUrlRewrite(true);

$product->save();

return true;

}

Mike D » 23 Aug 2011 » Reply

Ok, so now remove. Since we know we are getting here now.

print_r($importData['remove_all_images']);die("Remove Images Value");

and change the die two lines below that to

print_r("Now we are here");die();

and run the import again, and see if you get the red box that says "Now we are here"

Karr » 23 Aug 2011 » Reply

Got the ‘Now we are here’ note!

Mike D » 23 Aug 2011 » Reply

Ok, So now we know we are getting into the if statement that should remove the images related to the product.

Now do the following:
1. remove any lines that we added for the die() statements. so that it will not die.

2. clear the reports and logs. delete everything in /var/report and var/logs

3. Make sure that logging is enabled. This is in the config settings. Admin -> System -> configuration -> Developer -> Then you should see log setting in one of the field sets. Make sure logging is enabled.

4. Now run the import again. When it is finished see if any logs or reports were created. The logs should tell what/why the code is not working.

Karr » 23 Aug 2011 » Reply

Ha, worked like a charm!

If I was to place the code into the right place – it would have worked yesterday :) Human error is the cause to my misery :)

Thanks Mike!!!

Sohail » 13 Jan 2012 » Reply

This is great.
WOnderful tutorial, work a treat for me.

Thanks alot.

m4t » 12 Jun 2012 » Reply

Thanks, great code!

rjhartman » 27 Nov 2012 » Reply

Thanks Mike, the ‘removal’ worked fine on 1.4.0. Cheers.

Richard

Connie » 28 Jan 2013 » Reply

It worked for me very well!

Have your say!

Have your say!

Name *

Email *

Message

кредит онлайнбыстрый кредит