4

I'm currently working around one script which programmatically add products. Right now I have problem with the part that this script gets an image from URL and upload it to a directory and then use it as a product image.

I am using Magento 1.9.1.

So here is the part of the script which is supposed to take the image from the URL and upload it to the new product as product image:

$product = Mage::getModel('catalog/product')->load($new_product_id);

$url = 'http://media.asicdn.com/images/jpgo/6080000/6089330.jpg';
$img = '/media/catalog/product/images/image1.jpg';
file_put_contents($img, file_get_contents($url));

$product->setMediaGallery (array('images'=>array (), 'values'=>array ()));
$product->addImageToMediaGallery ($img , array ('image','small_image','thumbnail'), false, false);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); 

$product->save();

When I do that I receive error:

Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'Image does not exist.' in /home/superweb/public_html/sportsdirect/app/Mage.php:595 Stack trace: #0 /home/superweb/public_html/sportsdirect/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php(274): Mage::throwException('Image does not ...') #1 /home/superweb/public_html/sportsdirect/app/code/core/Mage/Catalog/Model/Product.php(1047): Mage_Catalog_Model_Product_Attribute_Backend_Media->addImage(Object(Mage_Catalog_Model_Product), '/media/catalog/...', Array, false, false) #2 /home/superweb/public_html/sportsdirect/SignProduct.php(63): Mage_Catalog_Model_Product->addImageToMediaGallery('/media/catalog/...', Array, false, false) #3 {main} thrown in /home/superweb/public_html/sportsdirect/app/Mage.php on line 595

The product is created but there is no image for the product.

1
  • Did it save the image in /media/? You may need to update your path to something like ../media/ relative to you script path Commented Jul 9, 2014 at 18:57

3 Answers 3

3

Hope this help

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

$image_url  = $data['productImg'];
$image_url  = str_replace("https://", "http://", $image_url); // replace https tp http
$image_type = substr(strrchr($image_url,"."),1); //find the image extension
$filename   = $data['productPartNumber'].'.'.$image_type; //give a new name, you can modify as per your requirement
$filepath   = Mage::getBaseDir('media') . DS . 'import'. DS . $filename; //path for temp storage folder: ./media/import/

$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$image_url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Cirkel');
$query = curl_exec($curl_handle);
curl_close($curl_handle);

Mage::Log('68. File Path ' . $filepath . ', image url ' . $image_url);

file_put_contents($filepath, $query); //store the image from external url to the temp storage folder file_get_contents(trim($image_url))
$filepath_to_image = $filepath;

if (file_exists($filepath_to_image)) {
    $newProduct->addImageToMediaGallery($filepath_to_image, array('image', 'small_image', 'thumbnail'), false, false);
    $newProduct->save();
}
Sign up to request clarification or add additional context in comments.

1 Comment

add try-catch to $product->save()
0

Bellow code works for me

$product = Mage::getModel('catalog/product')->load($productId);
$urlToImage = "SOME URL";
$mySaveDir = Mage::getBaseDir('media') . DS . 'my_images' . DS ;
$filename = basename($urlToImage);
$completeSaveLoc = $mySaveDir.$filename;
if(!file_exists($completeSaveLoc)){
    try {
        file_put_contents($completeSaveLoc,file_get_contents($urlToImage));
    }catch (Exception $e){

    }
}else{
    //echo "FILE EXIST " . $completeSaveLoc . "<br/>";
}
try {
    $product->addImageToMediaGallery($completeSaveLoc, array('image','thumbnail','small_image'), false);
$product->save();
} catch (Exception $e) {
   Mage::log($e->getMessage());
}

Comments

0
below code download the image agaisnst the skus in magento 2
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0); 
set_time_limit(0);
error_reporting(E_ALL);

$file = fopen('getImage.csv', 'r', '"'); // set path to the CSV file
require __DIR__ . '/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$directoryList = $objectManager->get('\Magento\Framework\App\Filesystem\DirectoryList');

// used for updating product stock - and it's important that it's inside the while loop
// $product = $objectManager->create('Magento\Catalog\Model\Product')->load();

$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/stockupdate-new.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

$header = fgetcsv($file); // get data headers and skip 1st row
$required_data_fields = 2;
$counter =0;
$row=1;
while ( $row = fgetcsv($file, 40000, ",") ) {

    $data = array();
    $data = array_combine($header, $row);
    $image_base = $data['image']; //this is for all images small_images ,thumbnail,base_image
    // $extension=".jpg";
    // $image_small = $data['small_image'];
    // $image_thumbnail = $data['thumbnail_image'];
    // $image_swatch = $data['swatch_image'];
    $image_addtional = $data['additional_images'];

    $sku = $data['sku'];
    // $urlToImage = "SOME URL";
    //foreach ($data as $key => $value) {
        //for ($i = 0; $i <=$key; $i++) {
            $mySaveDir =$directoryList->getPath('pub').'/media/newImg/'.$sku."-";
            $filename = basename($image_base);
            $completeSaveLoc = $mySaveDir.$filename.'.jpg';
            if(!file_exists($completeSaveLoc)){
                file_put_contents($completeSaveLoc,file_get_contents($image_base));
                echo "-------image is successfully downloaded-".$sku."-----";                
            }else{
                echo "this-". $sku."-img already downloaded------";
            }               
        //}

    //}
    }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.