in Magento, Programming, Web Development

Magento image not loading when using cron, only getting placeholder

I have a module which sends out an email via Mailchimp with a scheduled task for Magento’s internal cron and in doing so looks up the product image.

Mage::helper('catalog/image')->init($product, 'small_image')->resize(150));

The problem being only the placeholder was being returned when the cron job was executed. To confuse matters when I ran the script in testing from the browser it would return the correct image.

This is a nasty problem at first I thought this might be the answer Sangay details there that if your config does not specify a M,GB etc that it will return the wrong calculation, but then why the different results depending on how I ran the script?

To get to the bottom of this I ran what is being run in Mage_Catalog_Helper_Image

$model = Mage::getModel('catalog/product_image');
$model->setBaseFile($this->product->getData('small_image'))->resize(600,600);
$url = $model->saveFile()->getUrl();

PHP Fatal error:  Uncaught exception 'Varien_Exception' with message 'Memory limit has been reached.' in /lib/Varien/Image/Adapter/Gd2.php:58

Returning this shows the actual exception I did not get any Exception in the Mage exception log, and not in the host’s error log. On my part a server configuration oversight as the CLI php.ini did not have the error log set up. In any case that’s the error.

Because the value returned from _convertToByte function in Mage_Catalog_Helper_Image is -1 as the CLI php.ini sets the memory_limit to -1 (unlimited).

This could be an oversight by Magento or a design feature not to run this task on unlimited memory, personally I think it’s a bug. I modified the function to the following to set a 2G limit in this case.

   if (stripos($memoryValue, 'M') !== false) {
            return (int)$memoryValue * 1024 * 1024;
        }
        elseif (stripos($memoryValue, 'KB') !== false) {
            return (int)$memoryValue * 1024;
        }
        elseif ($memoryValue == "-1") {
            return '2147483648'; //2G
        }

Write a Comment

Comment

  1. Very Helpful
    I faced same issue. However I am not able to figure it out.
    Nice post. Keep It up.

    BTW
    I solved this problem by
    Mage::getModel(‘catalog/product_media_config’)
    ->getMediaUrl($_product->getSmallImage());

  2. Right now I am facing same kind of issue with cron. Not able to send email using sendTransactional function.

    While executing cron from admin(Aoe_Scheduler) its working fine but its not working when its schedule and executed by cron automaticaly

    Please help me if you have any solution.
    Thank you

    • What about something to do with store scope? You can run the observer in a test script setting the store beforehand to see what’s going on.

      Mage::app()->setCurrentStore(2);
      $observer = Mage::getModel('myapp/observer');
      $observer->myFunction();