Magento – How to add Product Image Programmatically in Magento 1.9.2

ce-1.9.2.2magento-1.9PHPproductproduct-images

Hello Guys I am creating product programmatically from frontend by submitting a form but when I am doing :

$this->getRequest()->getPost();

I am not getting the image data in array.

Also I want to add that in product how I can do that please guide me.

here the code of my frontend form :

<form action="<?php echo $this->getUrl('custom_abc/customProduct/addProduct') ?>" method="post" name="add-product" autocomplete="off" id="add-product-form" class="scaffold-form" enctype="multipart/form-data">
    <div class="field product-image">
        <label for="product-image" class="required"><em>*</em>Product Image</label>
        <div class="input-box">
            <input type="file" id="product-image" name="product-image" title="Product Image" class="input-text required-entry">
        </div>
    </div>
</form>

Here is the code of my product addition :

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$product = Mage::getModel('catalog/product')->load($productData['productId']);

try {
        $product
                ->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
                ->addImageToMediaGallery('not understanding what to do here', array('image', 'thumbnail', 'small_image'), false, false) //assigning image, thumb and small image to media gallery

        if ($product->save()) {

            Mage::getSingleton('core/session')->addSuccess('Your Product Uploaded Successfully');
            $this->_redirect('custom_abc/CustomAccount/manageCustomProduct');
            return;
        }else{

            Mage::getSingleton('core/session')->addError('Error in uploading Product');
            $this->_redirect('custom_abc/CustomAccount/manageCustomProduct');
            return;
        }
    } catch (Exception $e) {
        Mage::log($e->getMessage());
    }

Best Answer

Here is the working example

if(file_exists(Mage::getBaseDir('media') . DS . 'import' . DS . $gallery_img)){
        $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . DS . $gallery_img, null, false, false);
}

As you can see here, I have used full image path to the place where you have placed not understanding what to do here. Add your full imagepath to it.