PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

TYPO3: Scale and crop an image within a scheduler task

Note: This article was originally published at Planet PHP on 15 August 2012.
Planet PHP

At work I needed to scale and crop an image from within a TYPO3 scheduler task. TYPO3 is very powerful at image manipulation, but getting access to those methods turned out to be a problem.

Image manipulation in plugins is pretty easy: Call $cObj-getImgResource() with some configuration parameters and you're done.

Cron job scripts in TYPO3 don't have the full TYPO3 environment available - since they often do not need it - just like eID scripts. $cObj is missing, and loading it was non-trivial:

/* @var $cObj tslib_cObj */ chdir(PATH_site); if (!$GLOBALS['TSFE'] instanceof tslib_fe) { $GLOBALS['TSFE'] = t3lib_div::makeInstance('tslib_fe', $GLOBALS['TYPO3_CONF_VARS'], 0, 0); $GLOBALS['TSFE']-config['config']['language'] = null; $GLOBALS['TSFE']-initTemplate(); } if (!isset($GLOBALS['TT'])) { $GLOBALS['TT'] = t3lib_div::makeInstance('t3lib_TimeTrackNull'); } $GLOBALS['TSFE']-tmpl-getFileName_backPath = PATH_site; $cObj = t3lib_div::makeInstance('tslib_cObj');

Now that $cObj is available, we can crop and scale our image, and retrieve the path to it:

$arImageThumb = $cObj-getImgResource($origImgPath, array('width' = '200c-50', 'height' = '160c-50',)); $scaledImgPath = $arImageThumb[3];

This code scales the image down to exactly 200x160px, cropping everything off that's left over from top+bottom or left+right. The c-50 means centering and cropping from the mid of the image (centered, 50%).

Note that $origImgPath needs to be the path of the image relative to PATH_site, without a leading / - for example:

fileadmin/user_upload/foo.jpg