Add images to products programmatically in Magento

This post is almost the opposite of an earlier post (which you can read here) which outlined how to bulk remove images from products. This time we’re using a CSV upload, along with the files themselves, to add images to products in magento automatically. It’s quite quick and dirty, and assumes that you’ve just one image that you want to add to a product, and that it should be the main image, the small image and the thumbnail image for that product.

The first step is to create your CSV. It just needs two columns (and no header row) – the left hand column should contain the product SKU and the right hand column should contain the name of the image that you want want to be uploaded for that SKU. Upload that to the web root of your site with the name “images.csv” (or whatever you want – just remember what you’ve called it as you’ll need to refer to it in a minute).

Then upload the images – for ease of reference put these in a folder called “incoming” inside the “media” folder in the web root of your site.

Finally the script that does the hard work. You can download it at the foot of this post – the following explains what’s happening where.

Start off by linking into your Magento installation :

<?php 
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

Then set the name of the folder to which you’ve uploaded the images – if you’ve gone with “media / incoming” as outlined above, you won’t need to change this line. If you haven’t, you will..

$importDir = Mage::getBaseDir('media') . DS . 'incoming/';

Now let’s pick up the CSV file we uploaded – if you’ve called it anything other than “images.csv” you need to change this line accordingly :

$file_handle = fopen("images.csv", "r");

Now let’s loop through the CSV :

while (!feof($file_handle) ) {
	$line_of_text = fgetcsv($file_handle, 1024);

Then get the product SKU from the first column, and load the product itself into $ourProduct, then get the image’s filename from the second column – combine that with the directory location we set earlier to get the full path to the image.

	$productSKU = $line_of_text[0];
	$ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSKU);
	$fileName = $line_of_text[1];
	$filePath = $importDir.$fileName;

Then we can check if the file exists – if it does, then set it to be the main, small and thumbnail images for the selected SKU, and save the product :

	if (file_exists($filePath)) {
		$ourProduct->addImageToMediaGallery($filePath, array('image', 'small_image', 'thumbnail'), false, false);
		$ourProduct->save();

If it doesn’t, then output to the screen the SKU of the product so we know which ones it hasn’t worked for :

	} else {
		echo $productSKU . " not done";
		echo "\n";
	}	

Then finish off the file :

}
fclose($file_handle);
?>

Upload this file as add-images.php in the web root of your site, then visit www.yoursite.com/add-images.php in your browser to activate it. All being well, you’ll get a blank output after some thinking – any SKUs that it hasn’t worked for, you’ll be told about it.

18 comments

  • Bharat

    Hello,
    This is very good artical and thanks for your time.

    In my case it does not seem working.

    When script find image in the specified directory, it does not do anything. Does not go fro the next iteration as well. I added exception handling too but no luck. Not sure what to do. No error in error log file even.
    What I am getting on the browser is ..

    filePath /home/coralrush14/public_html/media/import/dn.8757.jpg8757 not done

    filePath /home/coralrush14/public_html/media/import/dn.9502.jpg

    File Exist. In if block

    Code:

    $filePath = $importDir.$fileName;
    echo “filePath “, $filePath ;
    if (file_exists($filePath)) {
    echo “File Exist. In if block”;
    # try
    {
    $ourProduct->addImageToMediaGallery($filePath, array(‘image’, ‘small_image’, ‘thumbnail’), false, false);
    echo “After calling addImageTo function”;
    $ourProduct->save();
    echo “After calling addImageTo and save function”;
    }
    #catch(Exception $e) {
    # echo ‘Message: ‘ .$e->getMessage();
    #}
    #echo “12 Bharat “;
    echo “”;
    }
    else {
    echo $productSKU . ” not done”;
    echo “”;
    }

    • Giles (author)

      Bharat,

      I would check (a) your code, and (b) the permissions on the var and media folders.

      Kind regards,

      Giles

  • stephen

    Nice one .Its great.Thank u..:-)

  • Sam

    Thanks for your article. Save me a lot of time 🙂

  • Polys

    Hello there. Thanks for the code.

    I did all as per the tutorial put I am getting the following error:

    sku not done

    Fatal error: Call to a member function addImageToMediaGallery() on a non-object in /home/shoebox/public_html/shop/add-images.php on line 14

    The SKU is real and the images is correct. I am trying to update Configurable products.

    • Giles (author)

      Either the SKU is wrong, or the image is wrong – debug it by asking the script to output the $filePath variable and the SKU that it thinks it’s adding the file to.

      Kind regards,

      Giles

  • Arun Sharma

    Hello Giles

    All things are working except .. I am not getting image at admin section for product . Means when i roll over the products image that area is blank. When i inspect that element then i see the path of image but . image not linked to that product . Please help .

  • cameleonwoman

    Thanks for the article. I tried your code and I received the following error:
    Fatal error: Call to a member function addImageToMediaGallery() on a non-object in /home/*****/public_html/magento/add-images.php on line 14

    I’m using the latest magento version 1.9.0

    • Giles (author)

      You’re welcome. Sounds like you’re trying to add an image to a SKU that doesn’t exist. I don’t think anything changed in 1.9 which would have impacted on this area – is this working for some items in your CSV then falling over?

      Giles

      • cameleonwoman

        Hi Giles,
        Obviously the mistake was from my side, and a stupid one. I didn’t put the image file extension (jpg) in the CSV. In my case the image file name is the same with the SKU, so I ended up with the following change in your code:

        line 11: $fileName = $line_of_text[0].’.jpg’;

        and of course my CSV has only one column for the SKU only.

        Thanks again for your code and for your quick reply.
        Going to update 1200 products with images.

        • Giles (author)

          No problem. Best of luck!

          Giles

  • Adnan

    thanx its work fine for me thank you very much

    • Giles (author)

      You’re welcome.

      Giles

  • kelhwang

    Can I also use this to add second, third and fourth images? Thanks

    • Giles (author)

      Yes, you can – just add the additional images as additional lines in the CSV. The first image in the list will be marked as the base / large / thumbnail image by default, though.

      Kind regards,

      Giles

        • Giles (author)

          You’re very welcome!

          Giles

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to talk to us about your project?