Magento – Programmatically adding images to products

magento-1productproduct-imagesprogrammatically

I am trying to create a system which automatically creates a configurable product and creates and associates simple products to it.
It is all working well but a lot of the simple products will be using the same images, by using the following code :

$product->addImageToMediaGallery('/var/www/test.jpg', $mediaAttribute, false, false);

It duplicates the image which is not what I wanted so I tried to do it this way:

$mediaGalleryData['images'][] =   array(
        'file'     => 'filepath here located in media/catalog dir',
        'position' => 0,
        'label'    => 'label',
        'disabled' => 0
    );

    $product->setData($attrCode, $mediaGalleryData);
    $product->save();

This does add an image to the product but somehow the filepath is changed to the one I provide extended by '_1', resulting into referring to a non existent file..

Is there any way to do this without getting the automatically asigned '_1' at the end of the file path?

Thanks!

Best Answer

You'll want to take a look at /app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php

Also, the easiest approach is using the API models to remove the image before reimporting:

Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
if ($product->getId()){
    $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
    $items = $mediaApi->items($product->getId());
    foreach($items as $item)
        $mediaApi->remove($product->getId(), $item['file']);
}

Some related: