Magento: Image upload script

Hey all, been a long time since I posted anything since my job is keeping me pretty busy…. here’s something I implemented for prettylittlething.com that might come in useful for you.

It’s a little script that basically scans a directory for images and, if it finds any, adds them to the relevant products.

Images have to be named as follows:

SKU-1.jpgSKU-2.jpg
SKU-3.jpg

ANOTHERSKU-1.jpgANOTHERSKU-2.jpg

etc…

here’s the script.  Drop it into your ‘shell’ directory and run it on a cronjob then just upload your images as and when required.

<?php
	$image_dir = "full/path/to/image/upload/directory/";

	require('abstract.php');
	//add images to array

	$search = "*-*.jpg";
	$images = glob($image_dir.$search);
	natcasesort($images);
	$image_array = array();
	foreach($images as $image){
		$filename = strtoupper($image);
		$name = basename($filename);
		$dat = explode("-",$name);
		$sku = $dat[0];
		$imagenum = explode(".",$dat[1]);
		$imagenum = $imagenum[0];
		$image_array[$sku][$imagenum] = $image;
	}
	if (count($image_array >= 1)){
		$output = "";
		foreach ($image_array as $sku=>$images){
			if (isset($images[1])){
				$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
				if ($product){
					$imgnum = 0;
					foreach($images as $image){
						$imgnum++;
						$image_attributes = null;
						if ($imgnum == 1)
							$image_attributes = array('image', 'small_image', 'thumbnail');
						$product->addImageToMediaGallery($image, $image_attributes, false, false);
						$output .= "$sku added ".basename($image)." to ".$product->getName()."\n";
					}
					$product->save();
					foreach($images as $image){
						unlink($image);
					}
				} else {
					$output .= "******* ERROR: can't find product for ".$sku." ********** \n";
				}
			} else {
				$output .= "******* ERROR: unable to locate image 1 for ".$sku." ********** \n";
			}

		}
		if ($output != ""){
			echo $ouput;
			//or you can email this somewhere
		}

	}

Leave a Reply

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