I'm currently writing a module which in its essence applies a pre-defined set of images to a product media gallery. It basically loops through a delimited list of filenames and uses addImageToMediaGallery to add the images to the product.

The code in the observer is:

        $ourProduct = $observer->getEvent()->getProduct();

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

        $tID =  $this->_getRequest()->getPost('template_id');
        $productsData = Mage::helper("imageimport")->getMedia($tID);

        foreach($productsData as $fileName){

            $filePath = trim($importDir. DS . $fileName);
            if($fileName!="") {
                if (file_exists($filePath)) {
                    $ourProduct->addImageToMediaGallery($filePath, array('image', 'small_image', 'thumbnail'), false, true);
                    Mage::log('Adding image '. $filePath .' to ' . $ourProduct->getSku(), null, 'imageimport.log');

                } else {
                    Mage::log('File does NOT exist: ' . $filePath, null, 'imageimport.log');
                    echo "<br>";

The problem I have with this is that it just creates another image in the media/catalog folder. This site has a buttload of products so having this feature will create needless duplicates of the same image.

So the question I'm posing is - within the confines of addImageToMediaGallery, am I able to simply reference an image instead of duplicating it?

If not, am I somehow able to utilize Magento's import dataflow behavior within an extension?

Hopefully I've titled this correctly - it's a strange question to ask.


1 Answer 1


Figured this out myself. Instead of wracking my head over import behavior, I decided to just execute SQL queries for now.

Since we had to create a faux folder location for these new images (ie t/s/t-shirt.jpg), I added this function:

public function mediaUrl($fileName){
    $chars = substr($fileName, 0,2);
    $chars = str_split($chars);
    $folder = "/" . implode('/', $chars);
    return $folder . "/" . $fileName;
    //t/r/trouser-front_6_1_2.png for example.

Initializing the connection:

$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$cpemg = $resource->getTableName('catalog_product_entity_media_gallery');

And then within the file_exists check (replacing addImageToMediaGallery): NOTE! 88 is the media_gallery attribute. MAKE SURE TO CHECK THIS IS STILL THE CASE OTHERWISE YOU WILL BURN

//Get url of image already in catalogue
$url = $this->mediaUrl($fileName);
$pId = $ourProduct->getId();

$insertQ = "INSERT INTO {$cpemg} (attribute_id,entity_id,value)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.