Set main product image in magento

How to set an image as default image for magento configurable products programmatically

 $importDir = Mage::getBaseDir('media') . DS;
 
 // main image
        if ($mainImage) {
            $image_directory = $dir . DS . 'data' . DS . $mainImage;
            if (file_exists($image_directory)) {
                $product->setMediaGallery(array('images' => array(), 'values' => array()))//media gallery initialization
                ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);//assigning image, thumb and small image to media gallery

            } else {
                $image_directory = $dir . 'data' . DS . 'comingsoon.jpg';
                $product->setMediaGallery(array('images' => array(), 'values' => array()))//media gallery initialization
                ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);
            }
        }

Share this Tutorial