2 /***************************************************************
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Standard graphical functions
30 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
35 * [CLASS/FUNCTION INDEX of SCRIPT]
39 * 155: class t3lib_stdGraphic
40 * 236: function init()
42 * SECTION: Layering images / "IMAGE" GIFBUILDER object
43 * 366: function maskImageOntoImage(&$im,$conf,$workArea)
44 * 436: function copyImageOntoImage(&$im,$conf,$workArea)
45 * 458: function copyGifOntoGif(&$im,$cpImg,$conf,$workArea)
46 * 537: function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h)
48 * SECTION: Text / "TEXT" GIFBUILDER object
49 * 587: function makeText(&$im,$conf,$workArea)
50 * 707: function txtPosition($conf,$workArea,$BB)
51 * 761: function calcBBox($conf)
52 * 820: function addToMap($cords,$conf)
53 * 843: function calcTextCordsForMap($cords,$offset, $conf)
54 * 878: function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1)
55 * 915: function fontResize($conf)
56 * 958: function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1)
57 * 1005: function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1)
58 * 1058: function splitString($string,$splitRendering,$fontSize,$fontFile)
59 * 1208: function calcWordSpacing($conf, $scaleFactor=1)
60 * 1227: function getTextScalFactor($conf)
62 * SECTION: Other GIFBUILDER objects related to TEXT
63 * 1262: function makeOutline(&$im,$conf,$workArea,$txtConf)
64 * 1291: function circleOffset($distance, $iterations)
65 * 1315: function makeEmboss(&$im,$conf,$workArea,$txtConf)
66 * 1337: function makeShadow(&$im,$conf,$workArea,$txtConf)
68 * SECTION: Other GIFBUILDER objects
69 * 1469: function makeBox(&$im,$conf,$workArea)
70 * 1491: function makeEffect(&$im, $conf)
71 * 1506: function IMparams($setup)
72 * 1589: function adjust(&$im, $conf)
73 * 1621: function crop(&$im,$conf)
74 * 1652: function scale(&$im,$conf)
75 * 1684: function setWorkArea($workArea)
77 * SECTION: Adjustment functions
78 * 1725: function autolevels(&$im)
79 * 1756: function outputLevels(&$im,$low,$high,$swap='')
80 * 1788: function inputLevels(&$im,$low,$high,$swap='')
81 * 1819: function reduceColors(&$im,$limit, $cols)
82 * 1832: function IMreduceColors($file, $cols)
84 * SECTION: GIFBUILDER Helper functions
85 * 1875: function prependAbsolutePath($fontFile)
86 * 1889: function v5_sharpen($factor)
87 * 1908: function v5_blur($factor)
88 * 1925: function randomName()
89 * 1938: function applyOffset($cords,$OFFSET)
90 * 1951: function convertColor($string)
91 * 2001: function recodeString($string)
92 * 2023: function singleChars($theText,$returnUnicodeNumber=FALSE)
93 * 2046: function objPosition($conf,$workArea,$BB)
95 * SECTION: Scaling, Dimensions of images
96 * 2125: function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0)
97 * 2238: function getImageDimensions($imageFile)
98 * 2266: function cacheImageDimensions($identifyResult)
99 * 2298: function getCachedImageDimensions($imageFile)
100 * 2332: function getImageScale($info,$w,$h,$options)
101 * 2438: function file_exists_typo3temp_file($output,$orig='')
103 * SECTION: ImageMagick API functions
104 * 2499: function imageMagickIdentify($imagefile)
105 * 2534: function imageMagickExec($input,$output,$params)
106 * 2557: function combineExec($input,$overlay,$mask,$output, $handleNegation = false)
107 * 2588: function wrapFileName($inputName)
109 * SECTION: Various IO functions
110 * 2629: function checkFile($file)
111 * 2643: function createTempSubDir($dirName)
112 * 2665: function applyImageMagickToPHPGif(&$im, $command)
113 * 2691: function gif_or_jpg($type,$w,$h)
114 * 2708: function output($file)
115 * 2748: function destroy()
116 * 2758: function imgTag ($imgInfo)
117 * 2770: function ImageWrite($destImg, $theImage)
118 * 2808: function imageGif($destImg, $theImage)
119 * 2820: function imageCreateFromGif($sourceImg)
120 * 2831: function imageCreateFromFile($sourceImg)
121 * 2870: function imagecreate($w, $h)
122 * 2885: function hexColor($col)
123 * 2903: function unifyColors(&$img, $colArr, $closest = false)
125 * TOTAL FUNCTIONS: 66
126 * (This index is automatically created/updated by the extension "extdeveval")
132 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick
133 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
135 * With TYPO3 4.4 GDlib 1.x support was dropped, also an option from config_default.php:
136 * $TYPO3_CONF_VARS['GFX']['gdlib_2'] = 0, // String/Boolean. Set this if you are using the new GDlib 2.0.1+. If you don't set this flag and still use GDlib2, you might encounter strange behaviours like black images etc. This feature might take effect only if ImageMagick is installed and working as well! You can also use the value "no_imagecopyresized_fix" - in that case it will NOT try to fix a known issue where "imagecopyresized" does not work correctly.
138 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
141 * @see tslib_gifBuilder
143 class t3lib_stdGraphic
{
145 // Internal configuration, set in init()
146 var $combineScript = 'combine'; // The ImageMagick filename used for combining two images. This name changed during the versions.
147 var $noFramePrepended = 0; // If set, there is no frame pointer prepended to the filenames.
148 var $GD2 = 1; // Set, if the GDlib used is version 2. @deprecated as of TYPO3 4.4, as this variables is now always set (GDlib2 always has this method, and PHP recommends to only use imagecreatetruecolor() over imagecreate())
149 var $imagecopyresized_fix = 0; // If set, imagecopyresized will not be called directly. For GD2 (some PHP installs?)
150 var $gifExtension = 'gif'; // This should be changed to 'png' if you want this class to read/make PNG-files instead!
151 var $gdlibExtensions = ''; // File formats supported by gdlib. This variable get's filled in "init" method
152 var $png_truecolor = FALSE; // Set to true if generated png's should be truecolor by default
153 var $truecolorColors = 0xffffff; // 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
154 var $enable_typo3temp_db_tracking = 0; // If set, then all files in typo3temp will be logged in a database table. In addition to being a log of the files with original filenames, it also serves to secure that the same image is not rendered simultaneously by two different processes.
155 var $imageFileExt = 'gif,jpg,jpeg,png,tif,bmp,tga,pcx,ai,pdf'; // Commalist of file extensions perceived as images by TYPO3. List should be set to 'gif,png,jpeg,jpg' if IM is not available. Lowercase and no spaces between!
156 var $webImageExt = 'gif,jpg,jpeg,png'; // Commalist of web image extensions (can be shown by a webbrowser)
157 var $maskNegate = ''; // Will be ' -negate' if ImageMagick ver 5.2+. See init();
158 var $NO_IM_EFFECTS = '';
163 'png' => '-colors 64'
165 var $NO_IMAGE_MAGICK = '';
167 var $im_version_4 = 0;
170 // Variables for testing, alternative usage etc.
171 var $filenamePrefix = ''; // Filename prefix for images scaled in imageMagickConvert()
172 var $imageMagickConvert_forceFileNameBody = ''; // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
173 var $dontCheckForExistingTempFile = 0; // This flag should always be false. If set true, imageMagickConvert will always write a new file to the tempdir! Used for debugging.
174 var $dontCompress = 0; // Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
175 var $dontUnlinkTempFiles = 0; // For debugging ONLY!
176 var $alternativeOutputKey = ''; // For debugging only. Filenames will not be based on mtime and only filename (not path) will be used. This key is also included in the hash of the filename...
179 var $IM_commands = array(); // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
180 var $workArea = array();
183 var $tempPath = 'typo3temp/'; // The temp-directory where to store the files. Normally relative to PATH_site but is allowed to be the absolute path AS LONG AS it is a subdir to PATH_site.
184 var $absPrefix = ''; // Prefix for relative paths. Used in "show_item.php" script. Is prefixed the output file name IN imageMagickConvert()
185 var $scalecmd = '-geometry'; // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
186 var $im5fx_blurSteps = '1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5'; // Used by v5_blur() to simulate 10 continuous steps of blurring
187 var $im5fx_sharpenSteps = '1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5'; // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
188 var $pixelLimitGif = 10000; // This is the limit for the number of pixels in an image before it will be rendered as JPG instead of GIF/PNG
189 var $colMap = array( // Array mapping HTML color names to RGB values.
190 'aqua' => array(0, 255, 255),
191 'black' => array(0, 0, 0),
192 'blue' => array(0, 0, 255),
193 'fuchsia' => array(255, 0, 255),
194 'gray' => array(128, 128, 128),
195 'green' => array(0, 128, 0),
196 'lime' => array(0, 255, 0),
197 'maroon' => array(128, 0, 0),
198 'navy' => array(0, 0, 128),
199 'olive' => array(128, 128, 0),
200 'purple' => array(128, 0, 128),
201 'red' => array(255, 0, 0),
202 'silver' => array(192, 192, 192),
203 'teal' => array(0, 128, 128),
204 'yellow' => array(255, 255, 0),
205 'white' => array(255, 255, 255)
209 * Charset conversion object:
214 var $nativeCharset = ''; // Is set to the native character set of the input strings.
218 * Init function. Must always call this when using the class.
219 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
224 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
226 if (function_exists('imagecreatefromjpeg') && function_exists('imagejpeg')) {
227 $this->gdlibExtensions
.= ',jpg,jpeg';
229 if (function_exists('imagecreatefrompng') && function_exists('imagepng')) {
230 $this->gdlibExtensions
.= ',png';
232 if (function_exists('imagecreatefromgif') && function_exists('imagegif')) {
233 $this->gdlibExtensions
.= ',gif';
235 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['png_truecolor']) {
236 $this->png_truecolor
= true;
238 if (!$gfxConf['im_version_5']) {
239 t3lib_div
::deprecationLog('The option $TYPO3_CONF_VARS[\'GFX\'][\'im_version_5\'] is not set, ImageMagic 4 is assumed. This is deprecated since TYPO3 4.5, support will be removed in TYPO3 4.6. Make sure to upgrade to ImageMagick version 6 or GraphichsMagick.');
240 $this->im_version_4
= true;
241 } elseif ($gfxConf['im_version_5'] === 'im5') {
242 t3lib_div
::deprecationLog('The option $TYPO3_CONF_VARS[\'GFX\'][\'im_version_5\'] is set to \'im5\'. This is deprecated since TYPO3 4.5, support will be removed in TYPO3 4.6. Make sure to upgrade to ImageMagick version 6 or GraphichsMagick.');
245 // When GIFBUILDER gets used in truecolor mode
246 // No colors parameter if we generate truecolor images.
247 if ($this->png_truecolor
) {
248 $this->cmds
['png'] = '';
251 // Setting default JPG parameters:
252 $this->jpegQuality
= t3lib_div
::intInRange($gfxConf['jpg_quality'], 10, 100, 75);
253 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -sharpen 50 -quality ' . $this->jpegQuality
;
255 if ($gfxConf['im_combine_filename']) {
256 $this->combineScript
= $gfxConf['im_combine_filename'];
258 if ($gfxConf['im_noFramePrepended']) {
259 $this->noFramePrepended
= 1;
262 // kept for backwards compatibility, can be turned on manually through localconf.php,
263 // but not through the installer anymore
264 $this->imagecopyresized_fix
= ($gfxConf['gdlib_2'] === 'no_imagecopyresized_fix' ?
0 : 1);
266 if ($gfxConf['gdlib_png']) {
267 $this->gifExtension
= 'png';
269 if ($gfxConf['enable_typo3temp_db_tracking']) {
270 $this->enable_typo3temp_db_tracking
= $gfxConf['enable_typo3temp_db_tracking'];
273 $this->imageFileExt
= $gfxConf['imagefile_ext'];
275 // This should be set if ImageMagick ver. 5+ is used.
276 if ($gfxConf['im_negate_mask']) {
277 // Boolean. Indicates if the mask images should be inverted first.
278 // This depends of the ImageMagick version. Below ver. 5.1 this should be false.
279 // Above ImageMagick version 5.2+ it should be true.
280 // Just set the flag if the masks works opposite the intension!
281 $this->maskNegate
= ' -negate';
283 if ($gfxConf['im_no_effects']) {
284 // Boolean. This is necessary if using ImageMagick 5+.
285 // Effects in Imagemagick 5+ tends to render very slowly!!
286 // - therefore must be disabled in order not to perform sharpen, blurring and such.
287 $this->NO_IM_EFFECTS
= 1;
289 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -quality ' . $this->jpegQuality
;
291 // ... but if 'im_v5effects' is set, don't care about 'im_no_effects'
292 if ($gfxConf['im_v5effects']) {
293 $this->NO_IM_EFFECTS
= 0;
294 $this->V5_EFFECTS
= 1;
296 if ($gfxConf['im_v5effects'] > 0) {
297 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -quality ' . intval($gfxConf['jpg_quality']) . $this->v5_sharpen(10);
301 if (!$gfxConf['im']) {
302 $this->NO_IMAGE_MAGICK
= 1;
304 // Secures that images are not scaled up.
305 if ($gfxConf['im_noScaleUp']) {
306 $this->mayScaleUp
= 0;
309 if (TYPO3_MODE
== 'FE') {
310 $this->csConvObj
= $GLOBALS['TSFE']->csConvObj
;
311 } elseif (is_object($GLOBALS['LANG'])) { // BE assumed:
312 $this->csConvObj
= $GLOBALS['LANG']->csConvObj
;
313 } else { // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
314 $this->csConvObj
= t3lib_div
::makeInstance('t3lib_cs');
316 $this->nativeCharset
= $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
320 /*************************************************
322 * Layering images / "IMAGE" GIFBUILDER object
324 *************************************************/
327 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is true.
328 * It reads the two images defined by $conf['file'] and $conf['mask'] and copies the $conf['file'] onto the input image pointer image using the $conf['mask'] as a grayscale mask
329 * The operation involves ImageMagick for combining.
331 * @param pointer GDlib image pointer
332 * @param array TypoScript array with configuration for the GIFBUILDER object.
333 * @param array The current working area coordinates.
335 * @see tslib_gifBuilder::make()
337 function maskImageOntoImage(&$im, $conf, $workArea) {
338 if ($conf['file'] && $conf['mask']) {
339 $imgInf = pathinfo($conf['file']);
340 $imgExt = strtolower($imgInf['extension']);
341 if (!t3lib_div
::inList($this->gdlibExtensions
, $imgExt)) {
342 $BBimage = $this->imageMagickConvert($conf['file'], $this->gifExtension
, '', '', '', '', '');
344 $BBimage = $this->getImageDimensions($conf['file']);
346 $maskInf = pathinfo($conf['mask']);
347 $maskExt = strtolower($maskInf['extension']);
348 if (!t3lib_div
::inList($this->gdlibExtensions
, $maskExt)) {
349 $BBmask = $this->imageMagickConvert($conf['mask'], $this->gifExtension
, '', '', '', '', '');
351 $BBmask = $this->getImageDimensions($conf['mask']);
353 if ($BBimage && $BBmask) {
356 $tmpStr = $this->randomName();
357 $theImage = $tmpStr . '_img.' . $this->gifExtension
;
358 $theDest = $tmpStr . '_dest.' . $this->gifExtension
;
359 $theMask = $tmpStr . '_mask.' . $this->gifExtension
;
360 // prepare overlay image
361 $cpImg = $this->imageCreateFromFile($BBimage[3]);
362 $destImg = imagecreatetruecolor($w, $h);
363 $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
364 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
365 $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
366 $this->ImageWrite($destImg, $theImage);
367 imageDestroy($cpImg);
368 imageDestroy($destImg);
369 // prepare mask image
370 $cpImg = $this->imageCreateFromFile($BBmask[3]);
371 $destImg = imagecreatetruecolor($w, $h);
372 $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
373 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
374 $this->copyGifOntoGif($destImg, $cpImg, $conf, $workArea);
375 $this->ImageWrite($destImg, $theMask);
376 imageDestroy($cpImg);
377 imageDestroy($destImg);
379 $this->ImageWrite($im, $theDest);
381 $this->combineExec($theDest, $theImage, $theMask, $theDest, TRUE); // Let combineExec handle maskNegation
383 $backIm = $this->imageCreateFromFile($theDest); // The main image is loaded again...
384 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
385 ImageColorTransparent($backIm, -1);
388 // unlink files from process
389 if (!$this->dontUnlinkTempFiles
) {
399 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is false (using only $conf['file'])
401 * @param pointer GDlib image pointer
402 * @param array TypoScript array with configuration for the GIFBUILDER object.
403 * @param array The current working area coordinates.
405 * @see tslib_gifBuilder::make(), maskImageOntoImage()
407 function copyImageOntoImage(&$im, $conf, $workArea) {
409 if (!t3lib_div
::inList($this->gdlibExtensions
, $conf['BBOX'][2])) {
410 $conf['BBOX'] = $this->imageMagickConvert($conf['BBOX'][3], $this->gifExtension
, '', '', '', '', '');
411 $conf['file'] = $conf['BBOX'][3];
413 $cpImg = $this->imageCreateFromFile($conf['file']);
414 $this->copyGifOntoGif($im, $cpImg, $conf, $workArea);
415 imageDestroy($cpImg);
420 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
422 * @param pointer GDlib image pointer, destination (bottom image)
423 * @param pointer GDlib image pointer, source (top image)
424 * @param array TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
425 * @param array Work area
426 * @return void Works on the $im image pointer
429 function copyGifOntoGif(&$im, $cpImg, $conf, $workArea) {
430 $cpW = imagesx($cpImg);
431 $cpH = imagesy($cpImg);
432 $tile = t3lib_div
::intExplode(',', $conf['tile']);
433 $tile[0] = t3lib_div
::intInRange($tile[0], 1, 20);
434 $tile[1] = t3lib_div
::intInRange($tile[1], 1, 20);
435 $cpOff = $this->objPosition($conf, $workArea, array($cpW * $tile[0], $cpH * $tile[1]));
437 for ($xt = 0; $xt < $tile[0]; $xt++
) {
438 $Xstart = $cpOff[0] +
$cpW * $xt;
439 if ($Xstart +
$cpW > $workArea[0]) { // if this image is inside of the workArea, then go on
441 if ($Xstart < $workArea[0]) {
442 $cpImgCutX = $workArea[0] - $Xstart;
443 $Xstart = $workArea[0];
447 $w = $cpW - $cpImgCutX;
448 if ($Xstart > $workArea[0] +
$workArea[2] - $w) {
449 $w = $workArea[0] +
$workArea[2] - $Xstart;
451 if ($Xstart < $workArea[0] +
$workArea[2]) { // if this image is inside of the workArea, then go on
453 for ($yt = 0; $yt < $tile[1]; $yt++
) {
454 $Ystart = $cpOff[1] +
$cpH * $yt;
455 if ($Ystart +
$cpH > $workArea[1]) { // if this image is inside of the workArea, then go on
456 if ($Ystart < $workArea[1]) {
457 $cpImgCutY = $workArea[1] - $Ystart;
458 $Ystart = $workArea[1];
462 $h = $cpH - $cpImgCutY;
463 if ($Ystart > $workArea[1] +
$workArea[3] - $h) {
464 $h = $workArea[1] +
$workArea[3] - $Ystart;
466 if ($Ystart < $workArea[1] +
$workArea[3]) { // if this image is inside of the workArea, then go on
467 $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
477 * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
479 * OK, the reason for this stupid fix is the following story:
480 * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
481 * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
482 * copy a color-ful image onto the destination.
484 * 1) Create a blank TRUE-COLOR image
485 * 2) Copy the destination image onto that one
486 * 3) Then do the actual operation; Copying the source (top image) onto that
487 * 4) ... and return the result pointer.
488 * 5) Reduce colors (if we do not, the result may become strange!)
489 * It works, but the resulting images is now a true-color PNG which may be very large.
490 * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
492 * For parameters, see PHP function "imagecopyresized()"
494 * @param pointer see PHP function "imagecopyresized()"
495 * @param pointer see PHP function "imagecopyresized()"
496 * @param integer see PHP function "imagecopyresized()"
497 * @param integer see PHP function "imagecopyresized()"
498 * @param integer see PHP function "imagecopyresized()"
499 * @param integer see PHP function "imagecopyresized()"
500 * @param integer see PHP function "imagecopyresized()"
501 * @param integer see PHP function "imagecopyresized()"
502 * @param integer see PHP function "imagecopyresized()"
503 * @param integer see PHP function "imagecopyresized()"
506 * @see t3lib_iconWorks::imagecopyresized()
508 function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h) {
509 if ($this->imagecopyresized_fix
) {
510 $im_base = imagecreatetruecolor(imagesx($im), imagesy($im)); // Make true color image
511 imagecopyresized($im_base, $im, 0, 0, 0, 0, imagesx($im), imagesy($im), imagesx($im), imagesy($im)); // Copy the source image onto that
512 imagecopyresized($im_base, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h); // Then copy the $cpImg onto that (the actual operation!)
513 $im = $im_base; // Set pointer
515 imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
520 /********************************
522 * Text / "TEXT" GIFBUILDER object
524 ********************************/
527 * Implements the "TEXT" GIFBUILDER object
529 * @param pointer GDlib image pointer
530 * @param array TypoScript array with configuration for the GIFBUILDER object.
531 * @param array The current working area coordinates.
533 * @see tslib_gifBuilder::make()
535 function makeText(&$im, $conf, $workArea) {
537 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf);
539 $txtPos = $this->txtPosition($conf, $workArea, $conf['BBOX']);
540 $theText = $this->recodeString($conf['text']);
542 if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
543 $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2], $txtPos, $conf['imgMap.']), $conf['imgMap.']);
545 if (!$conf['hideButCreateMap']) {
547 $cols = $this->convertColor($conf['fontColor']);
548 // NiceText is calculated
549 if (!$conf['niceText']) {
550 $Fcolor = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]);
551 // antiAliasing is setup:
552 $Fcolor = ($conf['antiAlias']) ?
$Fcolor : -$Fcolor;
554 for ($a = 0; $a < $conf['iterations']; $a++
) {
555 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
556 $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic
::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.']);
558 $this->renderTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf);
561 } else { // NICETEXT::
562 // options anti_aliased and iterations is NOT available when doing this!!
565 $tmpStr = $this->randomName();
567 $fileMenu = $tmpStr . '_menuNT.' . $this->gifExtension
;
568 $fileColor = $tmpStr . '_colorNT.' . $this->gifExtension
;
569 $fileMask = $tmpStr . '_maskNT.' . $this->gifExtension
;
571 $sF = t3lib_div
::intInRange($conf['niceText.']['scaleFactor'], 2, 5);
572 $newW = ceil($sF * imagesx($im));
573 $newH = ceil($sF * imagesy($im));
576 $maskImg = imagecreatetruecolor($newW, $newH);
577 $Bcolor = ImageColorAllocate($maskImg, 255, 255, 255);
578 ImageFilledRectangle($maskImg, 0, 0, $newW, $newH, $Bcolor);
579 $Fcolor = ImageColorAllocate($maskImg, 0, 0, 0);
580 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
581 $this->SpacedImageTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic
::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.'], $sF);
583 $this->renderTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf, $sF);
585 $this->ImageWrite($maskImg, $fileMask);
586 ImageDestroy($maskImg);
588 // Downscales the mask
589 if ($this->NO_IM_EFFECTS
) {
590 if ($this->maskNegate
) {
591 $command = trim($this->scalecmd
. ' ' . $w . 'x' . $h . '!'); // Negate 2 times makes no negate...
593 $command = trim($this->scalecmd
. ' ' . $w . 'x' . $h . '! -negate');
596 if ($this->maskNegate
) {
597 $command = trim($conf['niceText.']['before'] . ' ' . $this->scalecmd
. ' ' . $w . 'x' . $h . '! ' . $conf['niceText.']['after']);
599 $command = trim($conf['niceText.']['before'] . ' ' . $this->scalecmd
. ' ' . $w . 'x' . $h . '! ' . $conf['niceText.']['after'] . ' -negate');
601 if ($conf['niceText.']['sharpen']) {
602 if ($this->V5_EFFECTS
) {
603 $command .= $this->v5_sharpen($conf['niceText.']['sharpen']);
605 $command .= ' -sharpen ' . t3lib_div
::intInRange($conf['niceText.']['sharpen'], 1, 99);
610 $this->imageMagickExec($fileMask, $fileMask, $command);
612 // Make the color-file
613 $colorImg = imagecreatetruecolor($w, $h);
614 $Ccolor = ImageColorAllocate($colorImg, $cols[0], $cols[1], $cols[2]);
615 ImageFilledRectangle($colorImg, 0, 0, $w, $h, $Ccolor);
616 $this->ImageWrite($colorImg, $fileColor);
617 ImageDestroy($colorImg);
619 // The mask is applied
620 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
622 $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
624 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
625 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
626 ImageColorTransparent($backIm, -1);
630 // Deleting temporary files;
631 if (!$this->dontUnlinkTempFiles
) {
641 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
643 * @param array TypoScript array for the TEXT GIFBUILDER object
644 * @param array Workarea definition
645 * @param array Bounding box information, was set in tslib_gifBuilder::start()
646 * @return array [0]=x, [1]=y, [2]=w, [3]=h
650 function txtPosition($conf, $workArea, $BB) {
652 $angle = intval($conf['angle']) / 180 * pi();
654 $straightBB = $this->calcBBox($conf);
656 // offset, align, valign, workarea
657 $result = array(); // [0]=x, [1]=y, [2]=w, [3]=h
663 switch ($conf['align']) {
666 $factor = abs(cos($angle));
667 $sign = (cos($angle) < 0) ?
-1 : 1;
668 $len1 = $sign * $factor * $straightBB[0];
669 $len2 = $sign * $BB[0];
670 $result[0] = $w - ceil($len2 * $factor +
(1 - $factor) * $len1);
672 $factor = abs(sin($angle));
673 $sign = (sin($angle) < 0) ?
-1 : 1;
674 $len1 = $sign * $factor * $straightBB[0];
675 $len2 = $sign * $BB[1];
676 $result[1] = ceil($len2 * $factor +
(1 - $factor) * $len1);
679 switch ($conf['align']) {
683 $result[0] = round(($result[0]) / 2);
684 $result[1] = round(($result[1]) / 2);
691 $result = $this->applyOffset($result, t3lib_div
::intExplode(',', $conf['offset']));
692 $result = $this->applyOffset($result, $workArea);
697 * Calculates bounding box information for the TEXT GIFBUILDER object.
699 * @param array TypoScript array for the TEXT GIFBUILDER object
700 * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
702 * @see txtPosition(), tslib_gifBuilder::start()
704 function calcBBox($conf) {
705 $sF = $this->getTextScalFactor($conf);
706 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf, $sF);
707 $theText = $this->recodeString($conf['text']);
709 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $theText, $conf['splitRendering.'], $sF);
710 $theBBoxInfo = $charInf;
711 if ($conf['angle']) {
712 $xArr = array($charInf[0], $charInf[2], $charInf[4], $charInf[6]);
713 $yArr = array($charInf[1], $charInf[3], $charInf[5], $charInf[7]);
714 $x = max($xArr) - min($xArr);
715 $y = max($yArr) - min($yArr);
717 $x = ($charInf[2] - $charInf[0]);
718 $y = ($charInf[1] - $charInf[7]);
720 // Set original lineHeight (used by line breaks):
721 $theBBoxInfo['lineHeight'] = $y;
723 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
725 if (!$spacing && $wordSpacing) {
726 $bits = explode(' ', $theText);
727 foreach ($bits as $word) {
729 $wordInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $word, $conf['splitRendering.'], $sF);
730 $wordW = ($wordInf[2] - $wordInf[0]);
731 $x +
= $wordW +
$wordSpacing;
734 $utf8Chars = $this->singleChars($theText);
735 // For each UTF-8 char, do:
736 foreach ($utf8Chars as $char) {
737 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $char, $conf['splitRendering.'], $sF);
738 $charW = ($charInf[2] - $charInf[0]);
739 $x +
= $charW +
(($char == ' ') ?
$wordSpacing : $spacing);
742 } elseif (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($conf['text'], $conf) > $conf['breakWidth']) {
745 $breakWidth = $conf['breakWidth'];
746 $breakSpace = $this->getBreakSpace($conf, $theBBoxInfo);
748 $wordPairs = $this->getWordPairsForLineBreak($conf['text']);
749 // Iterate through all word pairs:
750 foreach ($wordPairs as $index => $wordPair) {
751 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
752 if ($index == 0 ||
$currentWidth +
$wordWidth <= $breakWidth) {
753 $currentWidth +
= $wordWidth;
755 $maxWidth = max($maxWidth, $currentWidth);
758 $currentWidth = $wordWidth;
761 $x = max($maxWidth, $currentWidth) * $sF;
767 if (is_array($theBBoxInfo)) {
768 foreach ($theBBoxInfo as &$value) {
769 $value = ceil($value / $sF);
773 return array($x, $y, $theBBoxInfo);
777 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
779 * @param array Coordinates for a polygon image map as created by ->calcTextCordsForMap()
780 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
783 * @see makeText(), calcTextCordsForMap()
785 function addToMap($cords, $conf) {
786 $JS = $conf['noBlur'] ?
'' : ' onfocus="blurLink(this);"';
788 $this->map
.= '<area' .
790 ' coords="' . implode(',', $cords) . '"' .
791 ' href="' . htmlspecialchars($conf['url']) . '"' .
792 ($conf['target'] ?
' target="' . htmlspecialchars($conf['target']) . '"' : '') .
794 (strlen($conf['titleText']) ?
' title="' . htmlspecialchars($conf['titleText']) . '"' : '') .
795 ' alt="' . htmlspecialchars($conf['altText']) . '" />';
799 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
801 * @param array Coordinates (from BBOX array)
802 * @param array Offset array
803 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
806 * @see makeText(), calcTextCordsForMap()
808 function calcTextCordsForMap($cords, $offset, $conf) {
809 $pars = t3lib_div
::intExplode(',', $conf['explode'] . ',');
811 $newCords[0] = $cords[0] +
$offset[0] - $pars[0];
812 $newCords[1] = $cords[1] +
$offset[1] +
$pars[1];
813 $newCords[2] = $cords[2] +
$offset[0] +
$pars[0];
814 $newCords[3] = $cords[3] +
$offset[1] +
$pars[1];
815 $newCords[4] = $cords[4] +
$offset[0] +
$pars[0];
816 $newCords[5] = $cords[5] +
$offset[1] - $pars[1];
817 $newCords[6] = $cords[6] +
$offset[0] - $pars[0];
818 $newCords[7] = $cords[7] +
$offset[1] - $pars[1];
824 * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
825 * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
828 * @param pointer (See argument for PHP function imageTTFtext())
829 * @param integer (See argument for PHP function imageTTFtext())
830 * @param integer (See argument for PHP function imageTTFtext())
831 * @param integer (See argument for PHP function imageTTFtext())
832 * @param integer (See argument for PHP function imageTTFtext())
833 * @param integer (See argument for PHP function imageTTFtext())
834 * @param string (See argument for PHP function imageTTFtext())
835 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
836 * @param integer The spacing of letters in pixels
837 * @param integer The spacing of words in pixels
838 * @param array $splitRenderingConf array
839 * @param integer Scale factor
843 function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF = 1) {
848 if (!$spacing && $wordSpacing) {
849 $bits = explode(' ', $text);
850 foreach ($bits as $word) {
852 $wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf, $sF);
853 $wordW = ($wordInf[2] - $wordInf[0]);
854 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
855 $x +
= $wordW +
$wordSpacing;
858 $utf8Chars = $this->singleChars($text);
859 // For each UTF-8 char, do:
860 foreach ($utf8Chars as $char) {
861 $charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
862 $charW = ($charInf[2] - $charInf[0]);
863 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
864 $x +
= $charW +
(($char == ' ') ?
$wordSpacing : $spacing);
870 * Function that finds the right fontsize that will render the textstring within a certain width
872 * @param array The TypoScript properties of the TEXT GIFBUILDER object
873 * @return integer The new fontSize
875 * @author René Fritz <r.fritz@colorcube.de>
876 * @see tslib_gifBuilder::start()
878 function fontResize($conf) {
879 // you have to use +calc options like [10.h] in 'offset' to get the right position of your text-image, if you use +calc in XY height!!!!
880 $maxWidth = intval($conf['maxWidth']);
881 list($spacing, $wordSpacing) = $this->calcWordSpacing($conf);
883 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
884 return $conf['fontSize'];
885 // ################ no calc for spacing yet !!!!!!
888 // determine bounding box.
889 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($conf['text']), $conf['splitRendering.']);
890 if ($conf['angle'] < 0) {
891 $pixelWidth = abs($bounds[4] - $bounds[0]);
892 } elseif ($conf['angle'] > 0) {
893 $pixelWidth = abs($bounds[2] - $bounds[6]);
895 $pixelWidth = abs($bounds[4] - $bounds[6]);
898 // Size is fine, exit:
899 if ($pixelWidth <= $maxWidth) {
904 } while ($conf['fontSize'] > 1);
908 return $conf['fontSize'];
912 * Wrapper for ImageTTFBBox
914 * @param integer (See argument for PHP function ImageTTFBBox())
915 * @param integer (See argument for PHP function ImageTTFBBox())
916 * @param string (See argument for PHP function ImageTTFBBox())
917 * @param string (See argument for PHP function ImageTTFBBox())
918 * @param array Split-rendering configuration
919 * @param integer Scale factor
920 * @return array Information array.
922 function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF = 1) {
925 $offsetInfo = array();
926 $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
928 // Traverse string parts:
929 foreach ($stringParts as $strCfg) {
930 $fontFile = t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']);
931 if (is_readable($fontFile)) {
933 // Calculate Bounding Box for part:
934 $calc = ImageTTFBBox(t3lib_div
::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);
936 // Calculate offsets:
937 if (!count($offsetInfo)) {
938 $offsetInfo = $calc; // First run, just copy over.
940 $offsetInfo[2] +
= $calc[2] - $calc[0] +
intval($splitRendering['compX']) +
intval($strCfg['xSpaceBefore']) +
intval($strCfg['xSpaceAfter']);
941 $offsetInfo[3] +
= $calc[3] - $calc[1] - intval($splitRendering['compY']) - intval($strCfg['ySpaceBefore']) - intval($strCfg['ySpaceAfter']);
942 $offsetInfo[4] +
= $calc[4] - $calc[6] +
intval($splitRendering['compX']) +
intval($strCfg['xSpaceBefore']) +
intval($strCfg['xSpaceAfter']);
943 $offsetInfo[5] +
= $calc[5] - $calc[7] - intval($splitRendering['compY']) - intval($strCfg['ySpaceBefore']) - intval($strCfg['ySpaceAfter']);
947 debug('cannot read file: ' . $fontFile, 't3lib_stdGraphic::ImageTTFBBoxWrapper()');
955 * Wrapper for ImageTTFText
957 * @param pointer (See argument for PHP function imageTTFtext())
958 * @param integer (See argument for PHP function imageTTFtext())
959 * @param integer (See argument for PHP function imageTTFtext())
960 * @param integer (See argument for PHP function imageTTFtext())
961 * @param integer (See argument for PHP function imageTTFtext())
962 * @param integer (See argument for PHP function imageTTFtext())
963 * @param string (See argument for PHP function imageTTFtext())
964 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
965 * @param array Split-rendering configuration
966 * @param integer Scale factor
969 function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF = 1) {
972 $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile);
976 // Traverse string parts:
977 foreach ($stringParts as $i => $strCfg) {
980 $colorIndex = $color;
982 // Set custom color if any (only when niceText is off):
983 if ($strCfg['color'] && $sF == 1) {
984 $cols = $this->convertColor($strCfg['color']);
985 $colorIndex = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]);
986 $colorIndex = $color >= 0 ?
$colorIndex : -$colorIndex;
989 // Setting xSpaceBefore
991 $x +
= intval($strCfg['xSpaceBefore']);
992 $y -= intval($strCfg['ySpaceBefore']);
995 $fontFile = t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']);
996 if (is_readable($fontFile)) {
999 ImageTTFText($im, t3lib_div
::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
1001 // Calculate offset to apply:
1002 $wordInf = ImageTTFBBox(t3lib_div
::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']);
1003 $x +
= $wordInf[2] - $wordInf[0] +
intval($splitRendering['compX']) +
intval($strCfg['xSpaceAfter']);
1004 $y +
= $wordInf[5] - $wordInf[7] - intval($splitRendering['compY']) - intval($strCfg['ySpaceAfter']);
1007 debug('cannot read file: ' . $fontFile, 't3lib_stdGraphic::ImageTTFTextWrapper()');
1014 * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
1016 * @param string UTF-8 string
1017 * @param array Split-rendering configuration from GIFBUILDER TEXT object.
1018 * @param integer Current fontsize
1019 * @param string Current font file
1020 * @return array Array with input string splitted according to configuration
1022 function splitString($string, $splitRendering, $fontSize, $fontFile) {
1024 // Initialize by setting the whole string and default configuration as the first entry.
1028 'fontSize' => $fontSize,
1029 'fontFile' => $fontFile
1032 // Traverse the split-rendering configuration:
1033 // Splitting will create more entries in $result with individual configurations.
1034 if (is_array($splitRendering)) {
1035 $sKeyArray = t3lib_TStemplate
::sortedKeyList($splitRendering);
1037 // Traverse configured options:
1038 foreach ($sKeyArray as $key) {
1039 $cfg = $splitRendering[$key . '.'];
1041 // Process each type of split rendering keyword:
1042 switch ((string) $splitRendering[$key]) {
1043 case 'highlightWord':
1044 if (strlen($cfg['value'])) {
1045 $newResult = array();
1047 // Traverse the current parts of the result array:
1048 foreach ($result as $part) {
1049 // Explode the string value by the word value to highlight:
1050 $explodedParts = explode($cfg['value'], $part['str']);
1051 foreach ($explodedParts as $c => $expValue) {
1052 if (strlen($expValue)) {
1053 $newResult[] = array_merge($part, array('str' => $expValue));
1055 if ($c +
1 < count($explodedParts)) {
1056 $newResult[] = array(
1057 'str' => $cfg['value'],
1058 'fontSize' => $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1059 'fontFile' => $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1060 'color' => $cfg['color'],
1061 'xSpaceBefore' => $cfg['xSpaceBefore'],
1062 'xSpaceAfter' => $cfg['xSpaceAfter'],
1063 'ySpaceBefore' => $cfg['ySpaceBefore'],
1064 'ySpaceAfter' => $cfg['ySpaceAfter'],
1070 // Set the new result as result array:
1071 if (count($newResult)) {
1072 $result = $newResult;
1077 if (strlen($cfg['value'])) {
1079 // Initialize range:
1080 $ranges = t3lib_div
::trimExplode(',', $cfg['value'], 1);
1081 foreach ($ranges as $i => $rangeDef) {
1082 $ranges[$i] = t3lib_div
::intExplode('-', $ranges[$i]);
1083 if (!isset($ranges[$i][1])) {
1084 $ranges[$i][1] = $ranges[$i][0];
1087 $newResult = array();
1089 // Traverse the current parts of the result array:
1090 foreach ($result as $part) {
1096 // Explode the string value by the word value to highlight:
1097 $utf8Chars = $this->singleChars($part['str']);
1098 foreach ($utf8Chars as $utfChar) {
1100 // Find number and evaluate position:
1101 $uNumber = $this->csConvObj
->utf8CharToUnumber($utfChar);
1103 foreach ($ranges as $rangeDef) {
1104 if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] ||
$uNumber <= $rangeDef[1])) {
1109 if ($currentState == -1) {
1110 $currentState = $inRange;
1111 } // Initialize first char
1114 if ($inRange != $currentState && !t3lib_div
::inList('32,10,13,9', $uNumber)) {
1117 if (strlen($bankAccum)) {
1118 $newResult[] = array(
1119 'str' => $bankAccum,
1120 'fontSize' => $currentState && $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1121 'fontFile' => $currentState && $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1122 'color' => $currentState ?
$cfg['color'] : '',
1123 'xSpaceBefore' => $currentState ?
$cfg['xSpaceBefore'] : '',
1124 'xSpaceAfter' => $currentState ?
$cfg['xSpaceAfter'] : '',
1125 'ySpaceBefore' => $currentState ?
$cfg['ySpaceBefore'] : '',
1126 'ySpaceAfter' => $currentState ?
$cfg['ySpaceAfter'] : '',
1130 // Initialize new settings:
1131 $currentState = $inRange;
1135 // Add char to bank:
1136 $bankAccum .= $utfChar;
1139 // Set result for FINAL part:
1140 if (strlen($bankAccum)) {
1141 $newResult[] = array(
1142 'str' => $bankAccum,
1143 'fontSize' => $currentState && $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1144 'fontFile' => $currentState && $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1145 'color' => $currentState ?
$cfg['color'] : '',
1146 'xSpaceBefore' => $currentState ?
$cfg['xSpaceBefore'] : '',
1147 'xSpaceAfter' => $currentState ?
$cfg['xSpaceAfter'] : '',
1148 'ySpaceBefore' => $currentState ?
$cfg['ySpaceBefore'] : '',
1149 'ySpaceAfter' => $currentState ?
$cfg['ySpaceAfter'] : '',
1154 // Set the new result as result array:
1155 if (count($newResult)) {
1156 $result = $newResult;
1168 * Calculates the spacing and wordSpacing values
1170 * @param array TypoScript array for the TEXT GIFBUILDER object
1171 * @param integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1172 * @return array Array with two keys [0]/[1] being array($spacing,$wordSpacing)
1176 function calcWordSpacing($conf, $scaleFactor = 1) {
1178 $spacing = intval($conf['spacing']);
1179 $wordSpacing = intval($conf['wordSpacing']);
1180 $wordSpacing = $wordSpacing ?
$wordSpacing : $spacing * 2;
1182 $spacing *= $scaleFactor;
1183 $wordSpacing *= $scaleFactor;
1185 return array($spacing, $wordSpacing);
1189 * Calculates and returns the niceText.scaleFactor
1191 * @param array TypoScript array for the TEXT GIFBUILDER object
1192 * @return integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1195 function getTextScalFactor($conf) {
1196 if (!$conf['niceText']) {
1198 } else { // NICETEXT::
1199 $sF = t3lib_div
::intInRange($conf['niceText.']['scaleFactor'], 2, 5);
1205 * Renders a regular text and takes care of a possible line break automatically.
1207 * @param pointer (See argument for PHP function imageTTFtext())
1208 * @param integer (See argument for PHP function imageTTFtext())
1209 * @param integer (See argument for PHP function imageTTFtext())
1210 * @param integer (See argument for PHP function imageTTFtext())
1211 * @param integer (See argument for PHP function imageTTFtext())
1212 * @param integer (See argument for PHP function imageTTFtext())
1213 * @param string (See argument for PHP function imageTTFtext())
1214 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1215 * @param array Split-rendering configuration
1216 * @param integer Scale factor
1217 * @param array $conf: The configuration
1220 protected function renderTTFText(&$im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $conf, $sF = 1) {
1221 if (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($string, $conf) > $conf['breakWidth']) {
1225 $breakWidth = $conf['breakWidth'];
1226 $breakSpace = $this->getBreakSpace($conf);
1228 $wordPairs = $this->getWordPairsForLineBreak($string);
1229 // Iterate through all word pairs:
1230 foreach ($wordPairs as $index => $wordPair) {
1231 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
1232 if ($index == 0 ||
$currentWidth +
$wordWidth <= $breakWidth) {
1233 $currentWidth +
= $wordWidth;
1234 $phrase .= $wordPair;
1236 // Render the current phrase that is below breakWidth:
1237 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1238 // Calculate the news height offset:
1240 // Restart the phrase:
1241 $currentWidth = $wordWidth;
1242 $phrase = $wordPair;
1245 // Render the remaining phrase:
1246 if ($currentWidth) {
1247 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1250 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
1255 * Gets the word pairs used for automatic line breaks.
1257 * @param string $string
1260 protected function getWordPairsForLineBreak($string) {
1261 $wordPairs = array();
1263 $wordsArray = preg_split('#([- .,!:]+)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE
);
1264 $wordsCount = count($wordsArray);
1265 for ($index = 0; $index < $wordsCount; $index +
= 2) {
1266 $wordPairs[] = $wordsArray[$index] . $wordsArray[$index +
1];
1273 * Gets the rendered text width.
1275 * @param string $text
1276 * @param array $conf
1279 protected function getRenderedTextWidth($text, $conf) {
1280 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($text), $conf['splitRendering.']);
1281 if ($conf['angle'] < 0) {
1282 $pixelWidth = abs($bounds[4] - $bounds[0]);
1283 } elseif ($conf['angle'] > 0) {
1284 $pixelWidth = abs($bounds[2] - $bounds[6]);
1286 $pixelWidth = abs($bounds[4] - $bounds[6]);
1292 * Gets the break space for each new line.
1294 * @param array $conf: TypoScript configuration for the currently rendered object
1295 * @param array $boundingBox: The bounding box the the currently rendered object
1296 * @return integer The break space
1298 protected function getBreakSpace($conf, array $boundingBox = NULL) {
1299 if (!isset($boundingBox)) {
1300 $boundingBox = $this->calcBBox($conf);
1301 $boundingBox = $boundingBox[2];
1304 if (isset($conf['breakSpace']) && $conf['breakSpace']) {
1305 $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
1307 $breakSpace = $boundingBox['lineHeight'];
1314 /*********************************************
1316 * Other GIFBUILDER objects related to TEXT
1318 *********************************************/
1321 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
1323 * @param pointer GDlib image pointer
1324 * @param array TypoScript array with configuration for the GIFBUILDER object.
1325 * @param array The current working area coordinates.
1326 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1328 * @see tslib_gifBuilder::make(), makeText()
1330 function makeOutline(&$im, $conf, $workArea, $txtConf) {
1331 $thickness = intval($conf['thickness']);
1333 $txtConf['fontColor'] = $conf['color'];
1334 $outLineDist = t3lib_div
::intInRange($thickness, 1, 2);
1335 for ($b = 1; $b <= $outLineDist; $b++
) {
1341 $outL = $this->circleOffset($b, $it);
1342 for ($a = 0; $a < $it; $a++
) {
1343 $this->makeText($im, $txtConf, $this->applyOffset($workArea, $outL[$a]));
1350 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
1354 * @param integer Distance
1355 * @param integer Iterations.
1357 * @see makeOutline()
1359 function circleOffset($distance, $iterations) {
1361 if ($distance && $iterations) {
1362 for ($a = 0; $a < $iterations; $a++
) {
1363 $yOff = round(sin(2 * pi() / $iterations * ($a +
1)) * 100 * $distance);
1365 $yOff = intval(ceil(abs($yOff / 100)) * ($yOff / abs($yOff)));
1367 $xOff = round(cos(2 * pi() / $iterations * ($a +
1)) * 100 * $distance);
1369 $xOff = intval(ceil(abs($xOff / 100)) * ($xOff / abs($xOff)));
1371 $res[$a] = array($xOff, $yOff);
1378 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
1380 * @param pointer GDlib image pointer
1381 * @param array TypoScript array with configuration for the GIFBUILDER object.
1382 * @param array The current working area coordinates.
1383 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1385 * @see tslib_gifBuilder::make(), makeShadow()
1387 function makeEmboss(&$im, $conf, $workArea, $txtConf) {
1388 $conf['color'] = $conf['highColor'];
1389 $this->makeShadow($im, $conf, $workArea, $txtConf);
1390 $newOffset = t3lib_div
::intExplode(',', $conf['offset']);
1391 $newOffset[0] *= -1;
1392 $newOffset[1] *= -1;
1393 $conf['offset'] = implode(',', $newOffset);
1394 $conf['color'] = $conf['lowColor'];
1395 $this->makeShadow($im, $conf, $workArea, $txtConf);
1399 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
1400 * The operation involves ImageMagick for combining.
1402 * @param pointer GDlib image pointer
1403 * @param array TypoScript array with configuration for the GIFBUILDER object.
1404 * @param array The current working area coordinates.
1405 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1407 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
1409 function makeShadow(&$im, $conf, $workArea, $txtConf) {
1410 $workArea = $this->applyOffset($workArea, t3lib_div
::intExplode(',', $conf['offset']));
1411 $blurRate = t3lib_div
::intInRange(intval($conf['blur']), 0, 99);
1413 if (!$blurRate ||
$this->NO_IM_EFFECTS
) { // No effects if ImageMagick ver. 5+
1414 $txtConf['fontColor'] = $conf['color'];
1415 $this->makeText($im, $txtConf, $workArea);
1419 $blurBorder = 3; // area around the blur used for cropping something
1420 $tmpStr = $this->randomName();
1421 $fileMenu = $tmpStr . '_menu.' . $this->gifExtension
;
1422 $fileColor = $tmpStr . '_color.' . $this->gifExtension
;
1423 $fileMask = $tmpStr . '_mask.' . $this->gifExtension
;
1425 // BlurColor Image laves
1426 $blurColImg = imagecreatetruecolor($w, $h);
1427 $bcols = $this->convertColor($conf['color']);
1428 $Bcolor = ImageColorAllocate($blurColImg, $bcols[0], $bcols[1], $bcols[2]);
1429 ImageFilledRectangle($blurColImg, 0, 0, $w, $h, $Bcolor);
1430 $this->ImageWrite($blurColImg, $fileColor);
1431 ImageDestroy($blurColImg);
1433 // The mask is made: BlurTextImage
1434 $blurTextImg = imagecreatetruecolor($w +
$blurBorder * 2, $h +
$blurBorder * 2);
1435 $Bcolor = ImageColorAllocate($blurTextImg, 0, 0, 0); // black background
1436 ImageFilledRectangle($blurTextImg, 0, 0, $w +
$blurBorder * 2, $h +
$blurBorder * 2, $Bcolor);
1437 $txtConf['fontColor'] = 'white';
1438 $blurBordArr = array($blurBorder, $blurBorder);
1439 $this->makeText($blurTextImg, $txtConf, $this->applyOffset($workArea, $blurBordArr));
1440 $this->ImageWrite($blurTextImg, $fileMask); // dump to temporary file
1441 ImageDestroy($blurTextImg); // destroy
1445 $command .= $this->maskNegate
;
1447 if ($this->V5_EFFECTS
) {
1448 $command .= $this->v5_blur($blurRate +
1);
1450 // Blurring of the mask
1451 $times = ceil($blurRate / 10); // How many blur-commands that is executed. Min = 1;
1452 $newBlurRate = $blurRate * 4; // Here I boost the blur-rate so that it is 100 already at 25. The rest is done by up to 99 iterations of the blur-command.
1453 $newBlurRate = t3lib_div
::intInRange($newBlurRate, 1, 99);
1454 for ($a = 0; $a < $times; $a++
) { // Building blur-command
1455 $command .= ' -blur ' . $blurRate;
1459 $this->imageMagickExec($fileMask, $fileMask, $command . ' +matte');
1461 $blurTextImg_tmp = $this->imageCreateFromFile($fileMask); // the mask is loaded again
1462 if ($blurTextImg_tmp) { // if nothing went wrong we continue with the blurred mask
1464 // cropping the border from the mask
1465 $blurTextImg = imagecreatetruecolor($w, $h);
1466 $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
1467 ImageDestroy($blurTextImg_tmp); // Destroy the temporary mask
1471 if ($conf['intensity']) {
1472 $intensity = t3lib_div
::intInRange($conf['intensity'], 0, 100);
1474 $intensity = ceil(255 - ($intensity / 100 * 255));
1475 $this->inputLevels($blurTextImg, 0, $intensity, $this->maskNegate
);
1477 $opacity = t3lib_div
::intInRange(intval($conf['opacity']), 0, 100);
1478 if ($opacity && $opacity < 100) {
1479 $high = ceil(255 * $opacity / 100);
1480 $this->outputLevels($blurTextImg, 0, $high, $this->maskNegate
); // reducing levels as the opacity demands
1483 $this->ImageWrite($blurTextImg, $fileMask); // Dump the mask again
1484 ImageDestroy($blurTextImg); // Destroy the mask
1486 // The pictures are combined
1487 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
1489 $this->combineExec($fileMenu, $fileColor, $fileMask, $fileMenu);
1491 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
1492 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
1493 ImageColorTransparent($backIm, -1);
1497 // Deleting temporary files;
1498 if (!$this->dontUnlinkTempFiles
) {
1507 /****************************
1509 * Other GIFBUILDER objects
1511 ****************************/
1514 * Implements the "BOX" GIFBUILDER object
1516 * @param pointer GDlib image pointer
1517 * @param array TypoScript array with configuration for the GIFBUILDER object.
1518 * @param array The current working area coordinates.
1520 * @see tslib_gifBuilder::make()
1522 function makeBox(&$im, $conf, $workArea) {
1523 $cords = t3lib_div
::intExplode(',', $conf['dimensions'] . ',,,');
1524 $conf['offset'] = $cords[0] . ',' . $cords[1];
1525 $cords = $this->objPosition($conf, $workArea, array($cords[2], $cords[3]));
1526 $cols = $this->convertColor($conf['color']);
1529 if (isset($conf['opacity'])) {
1531 // PHP 0 = opaque, 127 = transparent
1532 // TYPO3 100 = opaque, 0 = transparent
1533 $opacity = t3lib_div
::intInRange(intval($conf['opacity']), 1, 100, 1);
1534 $opacity = abs($opacity - 100);
1535 $opacity = round((127 * $opacity) / 100);
1538 $tmpColor = ImageColorAllocateAlpha($im, $cols[0], $cols[1], $cols[2], $opacity);
1539 imagefilledrectangle($im, $cords[0], $cords[1], $cords[0] +
$cords[2] - 1, $cords[1] +
$cords[3] - 1, $tmpColor);
1543 * Implements the "Ellipse" GIFBUILDER object
1544 * Example Typoscript:
1551 * 10.dimensions = 100,100,50,50
1555 * $conf['dimensions'] = offset x, offset y, width of ellipse, height of ellipse
1557 * @param pointer GDlib image pointer
1558 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1559 * @param array $workArea The current working area coordinates.
1561 * @see tslib_gifBuilder::make()
1563 public function makeEllipse(&$im, array $conf, array $workArea) {
1564 $ellipseConfiguration = t3lib_div
::intExplode(',', $conf['dimensions'] . ',,,');
1565 $conf['offset'] = $ellipseConfiguration[0] . ',' . $ellipseConfiguration[1]; // ellipse offset inside workArea (x/y)
1568 $imageCoordinates = $this->objPosition($conf, $workArea, array($ellipseConfiguration[2], $ellipseConfiguration[3]));
1570 $color = $this->convertColor($conf['color']);
1571 $fillingColor = imagecolorallocate($im, $color[0], $color[1], $color[2]);
1572 imagefilledellipse($im, $imageCoordinates[0], $imageCoordinates[1], $imageCoordinates[2], $imageCoordinates[3], $fillingColor);
1576 * Implements the "EFFECT" GIFBUILDER object
1577 * The operation involves ImageMagick for applying effects
1579 * @param pointer GDlib image pointer
1580 * @param array TypoScript array with configuration for the GIFBUILDER object.
1582 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
1584 function makeEffect(&$im, $conf) {
1585 $commands = $this->IMparams($conf['value']);
1587 $this->applyImageMagickToPHPGif($im, $commands);
1592 * Creating ImageMagick paramters from TypoScript property
1594 * @param string A string with effect keywords=value pairs separated by "|"
1595 * @return string ImageMagick prepared parameters.
1599 function IMparams($setup) {
1600 if (!trim($setup)) {
1603 $effects = explode('|', $setup);
1605 foreach ($effects as $val) {
1606 $pairs = explode('=', $val, 2);
1607 $value = trim($pairs[1]);
1608 $effect = strtolower(trim($pairs[0]));
1611 $commands .= ' -gamma ' . doubleval($value);
1614 if (!$this->NO_IM_EFFECTS
) {
1615 if ($this->V5_EFFECTS
) {
1616 $commands .= $this->v5_blur($value);
1618 $commands .= ' -blur ' . t3lib_div
::intInRange($value, 1, 99);
1623 if (!$this->NO_IM_EFFECTS
) {
1624 if ($this->V5_EFFECTS
) {
1625 $commands .= $this->v5_sharpen($value);
1627 $commands .= ' -sharpen ' . t3lib_div
::intInRange($value, 1, 99);
1632 $commands .= ' -rotate ' . t3lib_div
::intInRange($value, 0, 360);
1635 $commands .= ' -solarize ' . t3lib_div
::intInRange($value, 0, 99);
1638 $commands .= ' -swirl ' . t3lib_div
::intInRange($value, 0, 1000);
1641 $params = t3lib_div
::intExplode(',', $value);
1642 $commands .= ' -wave ' . t3lib_div
::intInRange($params[0], 0, 99) . 'x' . t3lib_div
::intInRange($params[1], 0, 99);
1645 $commands .= ' -charcoal ' . t3lib_div
::intInRange($value, 0, 100);
1648 $commands .= ' -colorspace GRAY';
1651 $commands .= ' -edge ' . t3lib_div
::intInRange($value, 0, 99);
1654 $commands .= ' -emboss';
1657 $commands .= ' -flip';
1660 $commands .= ' -flop';
1663 $commands .= ' -colors ' . t3lib_div
::intInRange($value, 2, 255);
1666 $commands .= ' -shear ' . t3lib_div
::intInRange($value, -90, 90);
1669 $commands .= ' -negate';
1677 * Implements the "ADJUST" GIFBUILDER object
1679 * @param pointer GDlib image pointer
1680 * @param array TypoScript array with configuration for the GIFBUILDER object.
1682 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1684 function adjust(&$im, $conf) {
1685 $setup = $conf['value'];
1686 if (!trim($setup)) {
1689 $effects = explode('|', $setup);
1690 foreach ($effects as $val) {
1691 $pairs = explode('=', $val, 2);
1692 $value = trim($pairs[1]);
1693 $effect = strtolower(trim($pairs[0]));
1695 case 'inputlevels': // low,high
1696 $params = t3lib_div
::intExplode(',', $value);
1697 $this->inputLevels($im, $params[0], $params[1]);
1699 case 'outputlevels':
1700 $params = t3lib_div
::intExplode(',', $value);
1701 $this->outputLevels($im, $params[0], $params[1]);
1704 $this->autoLevels($im);
1711 * Implements the "CROP" GIFBUILDER object
1713 * @param pointer GDlib image pointer
1714 * @param array TypoScript array with configuration for the GIFBUILDER object.
1716 * @see tslib_gifBuilder::make()
1718 function crop(&$im, $conf) {
1719 $this->setWorkArea(''); // clears workArea to total image
1720 $cords = t3lib_div
::intExplode(',', $conf['crop'] . ',,,');
1721 $conf['offset'] = $cords[0] . ',' . $cords[1];
1722 $cords = $this->objPosition($conf, $this->workArea
, array($cords[2], $cords[3]));
1724 $newIm = imagecreatetruecolor($cords[2], $cords[3]);
1725 $cols = $this->convertColor($conf['backColor'] ?
$conf['backColor'] : $this->setup
['backColor']);
1726 $Bcolor = ImageColorAllocate($newIm, $cols[0], $cols[1], $cols[2]);
1727 ImageFilledRectangle($newIm, 0, 0, $cords[2], $cords[3], $Bcolor);
1730 $workArea = array(0, 0, $cords[2], $cords[3]);
1731 if ($cords[0] < 0) {
1732 $workArea[0] = abs($cords[0]);
1734 $newConf['offset'] = -$cords[0];
1736 if ($cords[1] < 0) {
1737 $workArea[1] = abs($cords[1]);
1739 $newConf['offset'] .= ',' . -$cords[1];
1742 $this->copyGifOntoGif($newIm, $im, $newConf, $workArea);
1744 $this->w
= imagesx($im);
1745 $this->h
= imagesy($im);
1746 $this->setWorkArea(''); // clears workArea to total image
1750 * Implements the "SCALE" GIFBUILDER object
1752 * @param pointer GDlib image pointer
1753 * @param array TypoScript array with configuration for the GIFBUILDER object.
1755 * @see tslib_gifBuilder::make()
1757 function scale(&$im, $conf) {
1758 if ($conf['width'] ||
$conf['height'] ||
$conf['params']) {
1759 $tmpStr = $this->randomName();
1760 $theFile = $tmpStr . '.' . $this->gifExtension
;
1761 $this->ImageWrite($im, $theFile);
1762 $theNewFile = $this->imageMagickConvert($theFile, $this->gifExtension
, $conf['width'], $conf['height'], $conf['params'], '', '');
1763 $tmpImg = $this->imageCreateFromFile($theNewFile[3]);
1767 $this->w
= imagesx($im);
1768 $this->h
= imagesy($im);
1769 $this->setWorkArea(''); // clears workArea to total image
1771 if (!$this->dontUnlinkTempFiles
) {
1773 if ($theNewFile[3] && $theNewFile[3] != $theFile) {
1774 unlink($theNewFile[3]);
1781 * Implements the "WORKAREA" GIFBUILDER object when setting it
1782 * Setting internal working area boundaries (->workArea)
1784 * @param string Working area dimensions, comma separated
1787 * @see tslib_gifBuilder::make()
1789 function setWorkArea($workArea) {
1790 $this->workArea
= t3lib_div
::intExplode(',', $workArea);
1791 $this->workArea
= $this->applyOffset($this->workArea
, $this->OFFSET
);
1792 if (!$this->workArea
[2]) {
1793 $this->workArea
[2] = $this->w
;
1795 if (!$this->workArea
[3]) {
1796 $this->workArea
[3] = $this->h
;
1801 /*************************
1803 * Adjustment functions
1805 ************************/
1808 * Apply auto-levels to input image pointer
1810 * @param integer GDlib Image Pointer
1813 function autolevels(&$im) {
1814 $totalCols = ImageColorsTotal($im);
1817 for ($c = 0; $c < $totalCols; $c++
) {
1818 $cols = ImageColorsForIndex($im, $c);
1819 $grayArr[] = round(($cols['red'] +
$cols['green'] +
$cols['blue']) / 3);
1821 $min = min($grayArr);
1822 $max = max($grayArr);
1823 $delta = $max - $min;
1825 for ($c = 0; $c < $totalCols; $c++
) {
1826 $cols = ImageColorsForIndex($im, $c);
1827 $cols['red'] = floor(($cols['red'] - $min) / $delta * 255);
1828 $cols['green'] = floor(($cols['green'] - $min) / $delta * 255);
1829 $cols['blue'] = floor(($cols['blue'] - $min) / $delta * 255);
1830 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1836 * Apply output levels to input image pointer (decreasing contrast)
1838 * @param integer GDlib Image Pointer
1839 * @param integer The "low" value (close to 0)
1840 * @param integer The "high" value (close to 255)
1841 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1844 function outputLevels(&$im, $low, $high, $swap = '') {
1846 $low = t3lib_div
::intInRange($low, 0, 255);
1847 $high = t3lib_div
::intInRange($high, 0, 255);
1852 $high = 255 - $temp;
1855 $delta = $high - $low;
1856 $totalCols = ImageColorsTotal($im);
1857 for ($c = 0; $c < $totalCols; $c++
) {
1858 $cols = ImageColorsForIndex($im, $c);
1859 $cols['red'] = $low +
floor($cols['red'] / 255 * $delta);
1860 $cols['green'] = $low +
floor($cols['green'] / 255 * $delta);
1861 $cols['blue'] = $low +
floor($cols['blue'] / 255 * $delta);
1862 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1868 * Apply input levels to input image pointer (increasing contrast)
1870 * @param integer GDlib Image Pointer
1871 * @param integer The "low" value (close to 0)
1872 * @param integer The "high" value (close to 255)
1873 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1876 function inputLevels(&$im, $low, $high, $swap = '') {
1878 $low = t3lib_div
::intInRange($low, 0, 255);
1879 $high = t3lib_div
::intInRange($high, 0, 255);
1884 $high = 255 - $temp;
1887 $delta = $high - $low;
1888 $totalCols = ImageColorsTotal($im);
1889 for ($c = 0; $c < $totalCols; $c++
) {
1890 $cols = ImageColorsForIndex($im, $c);
1891 $cols['red'] = t3lib_div
::intInRange(($cols['red'] - $low) / $delta * 255, 0, 255);
1892 $cols['green'] = t3lib_div
::intInRange(($cols['green'] - $low) / $delta * 255, 0, 255);
1893 $cols['blue'] = t3lib_div
::intInRange(($cols['blue'] - $low) / $delta * 255, 0, 255);
1894 ImageColorSet($im, $c, $cols['red'], $cols['green'], $cols['blue']);
1900 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
1902 * @param string Image file to reduce
1903 * @param integer Number of colors to reduce the image to.
1904 * @return string Reduced file
1906 function IMreduceColors($file, $cols) {
1907 $fI = t3lib_div
::split_fileref($file);
1908 $ext = strtolower($fI['fileext']);
1909 $result = $this->randomName() . '.' . $ext;
1910 if (($reduce = t3lib_div
::intInRange($cols, 0, ($ext == 'gif' ?
256 : $this->truecolorColors
), 0)) > 0) {
1911 $params = ' -colors ' . $reduce;
1912 if (!$this->im_version_4
) {
1913 // IM4 doesn't have this options but forces them automatically if applicaple (<256 colors in image)
1914 if ($reduce <= 256) {
1915 $params .= ' -type Palette';
1917 if ($ext == 'png' && $reduce <= 256) {
1921 $this->imageMagickExec($file, $prefix . $result, $params);
1930 /*********************************
1932 * GIFBUILDER Helper functions
1934 *********************************/
1937 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
1938 * Use PATH_site unless we are in the backend.
1939 * Call it by t3lib_stdGraphic::prependAbsolutePath()
1941 * @param string The font file
1942 * @return string The font file with absolute path.
1944 function prependAbsolutePath($fontFile) {
1945 $absPath = defined('PATH_typo3') ?
dirname(PATH_thisScript
) . '/' : PATH_site
;
1946 $fontFile = t3lib_div
::isAbsPath($fontFile) ?
$fontFile : t3lib_div
::resolveBackPath($absPath . $fontFile);
1951 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
1952 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
1954 * @param integer The sharpening factor, 0-100 (effectively in 10 steps)
1955 * @return string The sharpening command, eg. " -sharpen 3x4"
1956 * @see makeText(), IMparams(), v5_blur()
1958 function v5_sharpen($factor) {
1959 $factor = t3lib_div
::intInRange(ceil($factor / 10), 0, 10);
1961 $sharpenArr = explode(',', ',' . $this->im5fx_sharpenSteps
);
1962 $sharpenF = trim($sharpenArr[$factor]);
1964 $cmd = ' -sharpen ' . $sharpenF;
1970 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
1971 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
1973 * @param integer The blurring factor, 0-100 (effectively in 10 steps)
1974 * @return string The blurring command, eg. " -blur 3x4"
1975 * @see makeText(), IMparams(), v5_sharpen()
1977 function v5_blur($factor) {
1978 $factor = t3lib_div
::intInRange(ceil($factor / 10), 0, 10);
1980 $blurArr = explode(',', ',' . $this->im5fx_blurSteps
);
1981 $blurF = trim($blurArr[$factor]);
1983 $cmd = ' -blur ' . $blurF;
1989 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
1990 * Used by functions in this class to create truely temporary files for the on-the-fly processing. These files will most likely be deleted right away.
1994 function randomName() {
1995 $this->createTempSubDir('temp/');
1996 return $this->tempPath
. 'temp/' . md5(uniqid(''));
2000 * Applies offset value to coordinated in $cords.
2001 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
2003 * @param array Integer coordinates in key 0/1
2004 * @param array Offset values in key 0/1
2005 * @return array Modified $cords array
2007 function applyOffset($cords, $OFFSET) {
2008 $cords[0] = intval($cords[0]) +
intval($OFFSET[0]);
2009 $cords[1] = intval($cords[1]) +
intval($OFFSET[1]);
2014 * Converts a "HTML-color" TypoScript datatype to RGB-values.
2017 * @param string "HTML-color" data type string, eg. 'red', '#ffeedd' or '255,0,255'. You can also add a modifying operator afterwards. There are two options: "255,0,255 : 20" - will add 20 to values, result is "255,20,255". Or "255,0,255 : *1.23" which will multiply all RGB values with 1.23
2018 * @return array RGB values in key 0/1/2 of the array
2020 function convertColor($string) {
2022 $cParts = explode(':', $string, 2);
2024 // Finding the RGB definitions of the color:
2025 $string = $cParts[0];
2026 if (strstr($string, '#')) {
2027 $string = preg_replace('/[^A-Fa-f0-9]*/', '', $string);
2028 $col[] = HexDec(substr($string, 0, 2));
2029 $col[] = HexDec(substr($string, 2, 2));
2030 $col[] = HexDec(substr($string, 4, 2));
2031 } elseif (strstr($string, ',')) {
2032 $string = preg_replace('/[^,0-9]*/', '', $string);
2033 $strArr = explode(',', $string);
2034 $col[] = intval($strArr[0]);
2035 $col[] = intval($strArr[1]);
2036 $col[] = intval($strArr[2]);
2038 $string = strtolower(trim($string));
2039 if ($this->colMap
[$string]) {
2040 $col = $this->colMap
[$string];
2042 $col = array(0, 0, 0);
2045 // ... and possibly recalculating the value
2046 if (trim($cParts[1])) {
2047 $cParts[1] = trim($cParts[1]);
2048 if (substr($cParts[1], 0, 1) == '*') {
2049 $val = doubleval(substr($cParts[1], 1));
2050 $col[0] = t3lib_div
::intInRange($col[0] * $val, 0, 255);
2051 $col[1] = t3lib_div
::intInRange($col[1] * $val, 0, 255);
2052 $col[2] = t3lib_div
::intInRange($col[2] * $val, 0, 255);
2054 $val = intval($cParts[1]);
2055 $col[0] = t3lib_div
::intInRange($col[0] +
$val, 0, 255);
2056 $col[1] = t3lib_div
::intInRange($col[1] +
$val, 0, 255);
2057 $col[2] = t3lib_div
::intInRange($col[2] +
$val, 0, 255);
2065 * Used with text strings for fonts when languages has other character sets.
2067 * @param string The text to recode
2068 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. { or &#quot; which should render as real chars).
2070 function recodeString($string) {
2071 // Recode string to UTF-8 from $this->nativeCharset:
2072 if ($this->nativeCharset
&& $this->nativeCharset
!= 'utf-8') {
2073 $string = $this->csConvObj
->utf8_encode($string, $this->nativeCharset
); // Convert to UTF-8
2080 * Split a string into an array of individual characters
2081 * The function will look at $this->nativeCharset and if that is set, the input string is expected to be UTF-8 encoded, possibly with entities in it. Otherwise the string is supposed to be a single-byte charset which is just splitted by a for-loop.
2083 * @param string The text string to split
2084 * @param boolean Return Unicode numbers instead of chars.
2085 * @return array Numerical array with a char as each value.
2087 function singleChars($theText, $returnUnicodeNumber = FALSE) {
2088 if ($this->nativeCharset
) {
2089 return $this->csConvObj
->utf8_to_numberarray($theText, 1, $returnUnicodeNumber ?
0 : 1); // Get an array of separated UTF-8 chars
2092 $c = strlen($theText);
2093 for ($a = 0; $a < $c; $a++
) {
2094 $output[] = substr($theText, $a, 1);
2101 * Create an array with object position/boundaries based on input TypoScript configuration (such as the "align" property is used), the work area definition and $BB array
2103 * @param array TypoScript configuration for a GIFBUILDER object
2104 * @param array Workarea definition
2105 * @param array BB (Bounding box) array. Not just used for TEXT objects but also for others
2106 * @return array [0]=x, [1]=y, [2]=w, [3]=h
2108 * @see copyGifOntoGif(), makeBox(), crop()
2110 function objPosition($conf, $workArea, $BB) {
2111 // offset, align, valign, workarea
2113 $result[2] = $BB[0];
2114 $result[3] = $BB[1];
2118 $align = explode(',', $conf['align']);
2119 $align[0] = strtolower(substr(trim($align[0]), 0, 1));
2120 $align[1] = strtolower(substr(trim($align[1]), 0, 1));
2122 switch ($align[0]) {
2124 $result[0] = $w - $result[2];
2127 $result[0] = round(($w - $result[2]) / 2);
2133 switch ($align[1]) {
2135 $result[1] = $h - $result[3]; // y pos
2138 $result[1] = round(($h - $result[3]) / 2);
2144 $result = $this->applyOffset($result, t3lib_div
::intExplode(',', $conf['offset']));
2145 $result = $this->applyOffset($result, $workArea);
2150 /***********************************
2152 * Scaling, Dimensions of images
2154 ***********************************/
2157 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
2159 * @param string The image filepath
2160 * @param string New extension, eg. "gif", "png", "jpg", "tif". If $newExt is NOT set, the new imagefile will be of the original format. If newExt = 'WEB' then one of the web-formats is applied.
2161 * @param string Width. $w / $h is optional. If only one is given the image is scaled proportionally. If an 'm' exists in the $w or $h and if both are present the $w and $h is regarded as the Maximum w/h and the proportions will be kept
2162 * @param string Height. See $w
2163 * @param string Additional ImageMagick parameters.
2164 * @param string Refers to which frame-number to select in the image. '' or 0 will select the first frame, 1 will select the next and so on...
2165 * @param array An array with options passed to getImageScale (see this function).
2166 * @param boolean If set, then another image than the input imagefile MUST be returned. Otherwise you can risk that the input image is good enough regarding messures etc and is of course not rendered to a new, temporary file in typo3temp/. But this option will force it to.
2167 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
2168 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
2170 function imageMagickConvert($imagefile, $newExt = '', $w = '', $h = '', $params = '', $frame = '', $options = '', $mustCreate = 0) {
2171 if ($this->NO_IMAGE_MAGICK
) {
2172 // Returning file info right away
2173 return $this->getImageDimensions($imagefile);
2176 if ($info = $this->getImageDimensions($imagefile)) {
2177 $newExt = strtolower(trim($newExt));
2178 if (!$newExt) { // If no extension is given the original extension is used
2181 if ($newExt == 'web') {
2182 if (t3lib_div
::inList($this->webImageExt
, $info[2])) {
2185 $newExt = $this->gif_or_jpg($info[2], $info[0], $info[1]);
2187 $params = $this->cmds
[$newExt];
2191 if (t3lib_div
::inList($this->imageFileExt
, $newExt)) {
2192 if (strstr($w . $h, 'm')) {
2198 $data = $this->getImageScale($info, $w, $h, $options);
2199 $w = $data['origW'];
2200 $h = $data['origH'];
2202 // if no conversion should be performed
2203 // this flag is true if the width / height does NOT dictate
2204 // the image to be scaled!! (that is if no width / height is
2205 // given or if the destination w/h matches the original image
2206 // dimensions or if the option to not scale the image is set)
2207 $noScale = (!$w && !$h) ||
($data[0] == $info[0] && $data[1] == $info[1]) ||
$options['noScale'];
2209 if ($noScale && !$data['crs'] && !$params && !$frame && $newExt == $info[2] && !$mustCreate) {
2210 // set the new width and height before returning,
2211 // if the noScale option is set
2212 if ($options['noScale']) {
2213 $info[0] = $data[0];
2214 $info[1] = $data[1];
2216 $info[3] = $imagefile;
2219 $info[0] = $data[0];
2220 $info[1] = $data[1];
2222 $frame = $this->noFramePrepended ?
'' : intval($frame);
2225 $params = $this->cmds
[$newExt];
2230 if (!$data['origW']) {
2231 $data['origW'] = $data[0];
2233 if (!$data['origH']) {
2234 $data['origH'] = $data[1];
2236 $offsetX = intval(($data[0] - $data['origW']) * ($data['cropH'] +
100) / 200);
2237 $offsetY = intval(($data[1] - $data['origH']) * ($data['cropV'] +
100) / 200);
2238 $params .= ' -crop ' . $data['origW'] . 'x' . $data['origH'] . '+' . $offsetX . '+' . $offsetY . ' ';
2241 $command = $this->scalecmd
. ' ' . $info[0] . 'x' . $info[1] . '! ' . $params . ' ';
2242 $cropscale = ($data['crs'] ?
'crs-V' . $data['cropV'] . 'H' . $data['cropH'] : '');
2244 if ($this->alternativeOutputKey
) {
2245 $theOutputName = t3lib_div
::shortMD5($command . $cropscale . basename($imagefile) . $this->alternativeOutputKey
. '[' . $frame . ']');
2247 $theOutputName = t3lib_div
::shortMD5($command . $cropscale . $imagefile . filemtime($imagefile) . '[' . $frame . ']');
2249 if ($this->imageMagickConvert_forceFileNameBody
) {
2250 $theOutputName = $this->imageMagickConvert_forceFileNameBody
;
2251 $this->imageMagickConvert_forceFileNameBody
= '';
2254 // Making the temporary filename:
2255 $this->createTempSubDir('pics/');
2256 $output = $this->absPrefix
. $this->tempPath
. 'pics/' . $this->filenamePrefix
. $theOutputName . '.' . $newExt;
2258 // Register temporary filename:
2259 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
2261 if ($this->dontCheckForExistingTempFile ||
!$this->file_exists_typo3temp_file($output, $imagefile)) {
2262 $this->imageMagickExec($imagefile, $output, $command, $frame);
2264 if (file_exists($output)) {
2267 if ($params) { // params could realisticly change some imagedata!
2268 $info = $this->getImageDimensions($info[3]);
2270 if ($info[2] == $this->gifExtension
&& !$this->dontCompress
) {
2271 t3lib_div
::gif_compress($info[3], ''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2280 * Gets the input image dimensions.
2282 * @param string The image filepath
2283 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2284 * @see imageMagickConvert(), tslib_cObj::getImgResource()
2286 function getImageDimensions($imageFile) {
2287 preg_match('/([^\.]*)$/', $imageFile, $reg);
2288 if (file_exists($imageFile) && t3lib_div
::inList($this->imageFileExt
, strtolower($reg[0]))) {
2289 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
2292 if ($temp = @getImageSize
($imageFile)) {
2293 $returnArr = array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
2295 $returnArr = $this->imageMagickIdentify($imageFile);
2298 $this->cacheImageDimensions($returnArr);
2307 * Cache the result of the getImageDimensions function into the database. Does not check if the
2310 * @param array $identifyResult: Result of the getImageDimensions function
2311 * @return boolean True if operation was successful
2312 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2314 function cacheImageDimensions($identifyResult) {
2315 // Create md5 hash of filemtime and filesize
2316 $md5Hash = md5(filemtime($identifyResult[3]) . filesize($identifyResult[3]));
2320 $fieldArray = array(
2321 'md5hash' => $md5Hash,
2322 'md5filename' => md5($identifyResult[3]),
2323 'tstamp' => $GLOBALS['EXEC_TIME'],
2324 'filename' => $identifyResult[3],
2325 'imagewidth' => $identifyResult[0],
2326 'imageheight' => $identifyResult[1],
2329 $GLOBALS['TYPO3_DB']->exec_INSERTquery(
2334 if (!$err = $GLOBALS['TYPO3_DB']->sql_error()) {
2343 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
2345 * @param string The image filepath
2346 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2347 * @author Michael Stucki <michael@typo3.org>
2348 * @author Robert Lemke <rl@robertlemke.de>
2350 function getCachedImageDimensions($imageFile) {
2351 // Create md5 hash of filemtime and filesize
2352 $md5Hash = md5(filemtime($imageFile) . filesize($imageFile));
2354 $cachedImageDimensions = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
2355 'md5hash, md5filename, imagewidth, imageheight',
2357 'md5filename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr(md5($imageFile), 'cache_imagesizes')
2361 if (is_array($cachedImageDimensions)) {
2362 if ($cachedImageDimensions['md5hash'] != $md5Hash) {
2363 // File has changed, delete the row
2364 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
2366 'md5filename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($cachedImageDimensions['md5filename'], 'cache_imagesizes')
2369 preg_match('/([^\.]*)$/', $imageFile, $imageExtension);
2371 (int)$cachedImageDimensions['imagewidth'],
2372 (int)$cachedImageDimensions['imageheight'],
2373 strtolower($imageExtension[0]),
2383 * Get numbers for scaling the image based on input
2385 * @param array Current image information: Width, Height etc.
2386 * @param integer "required" width
2387 * @param integer "required" height
2388 * @param array Options: Keys are like "maxW", "maxH", "minW", "minH"
2391 * @see imageMagickConvert()
2393 function getImageScale($info, $w, $h, $options) {
2394 if (strstr($w . $h, 'm')) {
2400 if (strstr($w . $h, 'c')) {
2401 $out['cropH'] = intval(substr(strstr($w, 'c'), 1));
2402 $out['cropV'] = intval(substr(strstr($h, 'c'), 1));
2411 // if there are max-values...
2412 if ($options['maxW']) {
2413 if ($w) { // if width is given...
2414 if ($w > $options['maxW']) {
2415 $w = $options['maxW'];
2416 $max = 1; // height should follow
2419 if ($info[0] > $options['maxW']) {
2420 $w = $options['maxW'];
2421 $max = 1; // height should follow
2425 if ($options['maxH']) {
2426 if ($h) { // if height is given...
2427 if ($h > $options['maxH']) {
2428 $h = $options['maxH'];
2429 $max = 1; // height should follow
2432 if ($info[1] > $options['maxH']) { // Changed [0] to [1] 290801
2433 $h = $options['maxH'];
2434 $max = 1; // height should follow
2442 if (!$this->mayScaleUp
) {
2443 if ($w > $info[0]) {
2446 if ($h > $info[1]) {
2450 if ($w ||
$h) { // if scaling should be performed
2452 $info[1] = ceil($info[1] * ($w / $info[0]));
2456 $info[0] = ceil($info[0] * ($h / $info[1]));
2461 $ratio = $info[0] / $info[1];
2462 if ($h * $ratio > $w) {
2463 $h = round($w / $ratio);
2465 $w = round($h * $ratio);
2469 $ratio = $info[0] / $info[1];
2470 if ($h * $ratio < $w) {
2471 $h = round($w / $ratio);
2473 $w = round($h * $ratio);
2482 // Set minimum-measures!
2483 if ($options['minW'] && $out[0] < $options['minW']) {
2484 if (($max ||
$crs) && $out[0]) {
2485 $out[1] = round($out[1] * $options['minW'] / $out[0]);
2487 $out[0] = $options['minW'];
2489 if ($options['minH'] && $out[1] < $options['minH']) {
2490 if (($max ||
$crs) && $out[1]) {
2491 $out[0] = round($out[0] * $options['minH'] / $out[1]);
2493 $out[1] = $options['minH'];
2500 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2502 * @param string Output imagefile
2503 * @param string Original basis file
2504 * @return boolean Returns true if the file is already being made; thus "true" means "Don't render the image again"
2507 function file_exists_typo3temp_file($output, $orig = '') {
2508 if ($this->enable_typo3temp_db_tracking
) {
2509 if (file_exists($output)) { // If file exists, then we return immediately
2511 } else { // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2512 $md5Hash = md5($output);
2513 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2515 'cache_typo3temp_log',
2516 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log') . ' AND tstamp>' . ($GLOBALS['EXEC_TIME'] - 30)
2518 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // If there was a record, the image is being generated by another proces (we assume)
2519 if (is_object($GLOBALS['TSFE'])) {
2520 $GLOBALS['TSFE']->set_no_cache();
2521 } // ...so we set no_cache, because we dont want this page (which will NOT display an image...!) to be cached! (Only a page with the correct image on...)
2522 if (is_object($GLOBALS['TT'])) {
2523 $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: ' . $output);
2525 return 2; // Return 'success - 2'
2526 } else { // If the current time is more than 30 seconds since this record was written, we clear the record, write a new and render the image.
2528 $insertFields = array(
2529 'md5hash' => $md5Hash,
2530 'tstamp' => $GLOBALS['EXEC_TIME'],
2531 'filename' => $output,
2532 'orig_filename' => $orig
2534 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
2535 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2537 if (is_object($GLOBALS['TT'])) {
2538 $GLOBALS['TT']->setTSlogMessage('typo3temp_log: The row did not exist, so a new is written and file is being processed: ' . $output);
2544 return file_exists($output);
2549 /***********************************
2551 * ImageMagick API functions
2553 ***********************************/
2556 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2559 * @param string The relative (to PATH_site) image filepath
2562 function imageMagickIdentify($imagefile) {
2563 if (!$this->NO_IMAGE_MAGICK
) {
2564 $frame = $this->noFramePrepended ?
'' : '[0]';
2565 $cmd = t3lib_div
::imageMagickCommand('identify', $this->wrapFileName($imagefile) . $frame);
2566 $returnVal = array();
2567 t3lib_utility_Command
::exec($cmd, $returnVal);
2568 $splitstring = $returnVal[0];
2569 $this->IM_commands
[] = array('identify', $cmd, $returnVal[0]);
2571 preg_match('/([^\.]*)$/', $imagefile, $reg);
2572 $splitinfo = explode(' ', $splitstring);
2573 foreach ($splitinfo as $key => $val) {
2576 $temp = explode('x', $val);
2578 if (intval($temp[0]) && intval($temp[1])) {
2583 if ($dim[0] && $dim[1]) {
2584 return array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2591 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2592 * Can be used for many things, mostly scaling and effects.
2594 * @param string The relative (to PATH_site) image filepath, input file (read from)
2595 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2596 * @param string ImageMagick parameters
2597 * @param integer Optional, refers to which frame-number to select in the image. '' or 0
2598 * will select the first frame, 1 will select the next and so on...
2599 * @return string The result of a call to PHP function "exec()"
2601 function imageMagickExec($input, $output, $params, $frame = 0) {
2602 if (!$this->NO_IMAGE_MAGICK
) {
2604 // Unless noFramePrepended is set in the Install Tool, a frame number is added to
2605 // select a specific page of the image (by default this will be the first page)
2606 if (!$this->noFramePrepended
) {
2607 $frame = '[' . intval($frame) . ']';
2612 $cmd = t3lib_div
::imageMagickCommand('convert', $params . ' ' . $this->wrapFileName($input) . $frame . ' ' . $this->wrapFileName($output));
2613 $this->IM_commands
[] = array($output, $cmd);
2615 $ret = t3lib_utility_Command
::exec($cmd);
2616 t3lib_div
::fixPermissions($output); // Change the permissions of the file
2623 * Executes a ImageMagick "combine" (or composite in newer times) on four filenames - $input, $overlay and $mask as input files and $output as the output filename (written to)
2624 * Can be used for many things, mostly scaling and effects.
2626 * @param string The relative (to PATH_site) image filepath, bottom file
2627 * @param string The relative (to PATH_site) image filepath, overlay file (top)
2628 * @param string The relative (to PATH_site) image filepath, the mask file (grayscale)
2629 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2630 * @param [type] $handleNegation: ...
2633 function combineExec($input, $overlay, $mask, $output, $handleNegation = FALSE) {
2634 if (!$this->NO_IMAGE_MAGICK
) {
2635 $params = '-colorspace GRAY +matte';
2636 if ($handleNegation) {
2637 if ($this->maskNegate
) {
2638 $params .= ' ' . $this->maskNegate
;
2641 $theMask = $this->randomName() . '.' . $this->gifExtension
;
2642 $this->imageMagickExec($mask, $theMask, $params);
2643 $cmd = t3lib_div
::imageMagickCommand('combine', '-compose over +matte ' . $this->wrapFileName($input) . ' ' . $this->wrapFileName($overlay) . ' ' . $this->wrapFileName($theMask) . ' ' . $this->wrapFileName($output)); // +matte = no alpha layer in output
2644 $this->IM_commands
[] = array($output, $cmd);
2646 $ret = t3lib_utility_Command
::exec($cmd);
2647 t3lib_div
::fixPermissions($output); // Change the permissions of the file
2649 if (is_file($theMask)) {
2658 * Escapes a file name so it can safely be used on the command line.
2660 * @param string $inputName filename to safeguard, must not be empty
2662 * @return string $inputName escaped as needed
2664 protected function wrapFileName($inputName) {
2665 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
2666 $currentLocale = setlocale(LC_CTYPE
, 0);
2667 setlocale(LC_CTYPE
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
2669 $escapedInputName = escapeshellarg($inputName);
2670 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
2671 setlocale(LC_CTYPE
, $currentLocale);
2673 return $escapedInputName;
2677 /***********************************
2679 * Various IO functions
2681 ***********************************/
2684 * Returns true if the input file existed
2686 * @param string Input file to check
2687 * @return string Returns the filename if the file existed, otherwise empty.
2689 function checkFile($file) {
2690 if (@is_file
($file)) {
2698 * Creates subdirectory in typo3temp/ if not already found.
2700 * @param string Name of sub directory
2701 * @return boolean Result of t3lib_div::mkdir(), true if it went well.
2703 function createTempSubDir($dirName) {
2705 // Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
2706 if (t3lib_div
::isFirstPartOfStr($this->tempPath
, PATH_site
)) {
2707 $tmpPath = $this->tempPath
;
2709 $tmpPath = PATH_site
. $this->tempPath
;
2712 // Making the temporary filename:
2713 if (!@is_dir
($tmpPath . $dirName)) {
2714 return t3lib_div
::mkdir($tmpPath . $dirName);
2719 * Applies an ImageMagick parameter to a GDlib image pointer resource by writing the resource to file, performing an IM operation upon it and reading back the result into the ImagePointer.
2721 * @param pointer The image pointer (reference)
2722 * @param string The ImageMagick parameters. Like effects, scaling etc.
2725 function applyImageMagickToPHPGif(&$im, $command) {
2726 $tmpStr = $this->randomName();
2727 $theFile = $tmpStr . '.' . $this->gifExtension
;
2728 $this->ImageWrite($im, $theFile);
2729 $this->imageMagickExec($theFile, $theFile, $command);
2730 $tmpImg = $this->imageCreateFromFile($theFile);
2734 $this->w
= imagesx($im);
2735 $this->h
= imagesy($im);
2737 if (!$this->dontUnlinkTempFiles
) {
2743 * Returns an image extension for an output image based on the number of pixels of the output and the file extension of the original file.
2744 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2746 * @param string The file extension, lowercase.
2747 * @param integer The width of the output image.
2748 * @param integer The height of the output image.
2749 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2751 function gif_or_jpg($type, $w, $h) {
2752 if ($type == 'ai' ||
$w * $h < $this->pixelLimitGif
) {
2753 return $this->gifExtension
;
2760 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2761 * Used in GIFBUILDER
2762 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
2764 * @param string The filename to write to.
2765 * @return string Returns input filename
2766 * @see tslib_gifBuilder::gifBuild()
2768 function output($file) {
2771 preg_match('/([^\.]*)$/', $file, $reg);
2772 $ext = strtolower($reg[0]);
2776 if ($this->ImageWrite($this->im
, $file)) {
2777 // ImageMagick operations
2778 if ($this->setup
['reduceColors'] ||
!$this->png_truecolor
) {
2779 $reduced = $this->IMreduceColors($file, t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256));
2781 @copy
($reduced, $file);
2785 t3lib_div
::gif_compress($file, 'IM'); // Compress with IM! (adds extra compression, LZW from ImageMagick) (Workaround for the absence of lzw-compression in GD)
2790 $quality = 0; // Use the default
2791 if ($this->setup
['quality']) {
2792 $quality = t3lib_div
::intInRange($this->setup
['quality'], 10, 100);
2794 if ($this->ImageWrite($this->im
, $file, $quality)) {
2799 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $file;
2805 * Destroy internal image pointer, $this->im
2808 * @see tslib_gifBuilder::gifBuild()
2810 function destroy() {
2811 ImageDestroy($this->im
);
2815 * Returns Image Tag for input image information array.
2817 * @param array Image information array, key 0/1 is width/height and key 3 is the src value
2818 * @return string Image tag for the input image information array.
2820 function imgTag($imgInfo) {
2821 return '<img src="' . $imgInfo[3] . '" width="' . $imgInfo[0] . '" height="' . $imgInfo[1] . '" border="0" alt="" />';
2825 * Writes the input GDlib image pointer to file
2827 * @param pointer The GDlib image resource pointer
2828 * @param string The filename to write to
2829 * @param integer The image quality (for JPEGs)
2830 * @return boolean The output of either imageGif, imagePng or imageJpeg based on the filename to write
2831 * @see maskImageOntoImage(), scale(), output()
2833 function ImageWrite($destImg, $theImage, $quality = 0) {
2834 imageinterlace($destImg, 0);
2835 $ext = strtolower(substr($theImage, strrpos($theImage, '.') +
1));
2840 if (function_exists('imageJpeg')) {
2841 if ($quality == 0) {
2842 $quality = $this->jpegQuality
;
2844 $result = imageJpeg($destImg, $theImage, $quality);
2848 if (function_exists('imageGif')) {
2849 imagetruecolortopalette($destImg, TRUE, 256);
2850 $result = imageGif($destImg, $theImage);
2854 if (function_exists('imagePng')) {
2855 $result = ImagePng($destImg, $theImage);
2860 t3lib_div
::fixPermissions($theImage);
2866 * Creates a new GDlib image resource based on the input image filename.
2867 * If it fails creating a image from the input file a blank gray image with the dimensions of the input image will be created instead.
2869 * @param string Image filename
2870 * @return pointer Image Resource pointer
2872 function imageCreateFromFile($sourceImg) {
2873 $imgInf = pathinfo($sourceImg);
2874 $ext = strtolower($imgInf['extension']);