Friday, 4 May 2012

Adding mass upload image in existing product

In Magento Many a times we need to upload images to the existing products
It will be two way
1. Image with other details like Image Label, Image Position etc
2. Images only.
Here is the code.


include('app/Mage.php');
Mage::app('admin');
set_time_limit(0);
error_reporting(E_ALL ^ E_NOTICE);


$path = "batch1_image.csv"; //tilde separated csv
$abc = file_get_contents($path,'rb') or die("File not found");
$users = explode("\n",$abc);

echo "
";
$heads = split("~",$users[0]); //taking first row as key
$limit= count($users)-1;
$start=1;
$imagePath=Mage::getBaseDir('media')."/import/batch1_image/"; //folder in which images exits
$model = Mage::getModel('catalog/product_attribute_media_api');

for ($i=$start; $i < $limit; $i++ )
{
$fields = split("~",$users[$i]);
for($j=0; $j < count($heads); $j++ )
{
$currentProduct[stripQuotes($heads[$j])]=stripQuotes($fields[$j]);
}
//print_r($currentProduct); //exit;
$product = Mage::getModel('catalog/product');
$sku=$currentProduct['SKU'];
$_product = $product->loadByAttribute('sku', $sku);

if($_product)
{

$productId=$_product->getId();
$product = Mage::getModel('catalog/product')->load($productId);

$imageName=$currentProduct['Image Name'];

if($imageName!="")
{
$_gallery = $product->getMediaGalleryImages();
$imgcount = $product->getMediaGalleryImages()->count();

$label=$currentProduct['Image Label'];
$imagefile= $imagePath.$imageName;
if(file_exists($imagefile))
{
$newImage = array(
'file' => array(
'content' => base64_encode(file_get_contents($imagefile)),
'mime' => 'image/jpeg',
'name' => $imageName
),
'label' => $label,
'position' => $imgcount+1, // = sortorder
'types' => array('image', 'small_image', 'thumbnail'),
'exclude' => 0
);
$model->create($sku, $newImage);

//this code is functional if you need not to update Image label, position
//$product->addImageToMediaGallery($imagefile,array('image','small_image'),false,false); //3 rd parameter
//$product->save();

}
else
{
echo "\n
File $imagefile not found";
}

}
}


//break;
} //End of for loop


//to remove single quote from both side.
function stripQuotes($str)
{
$str=substr($str,1,-1);
return $str;
}

No comments :

Post a Comment