2 /***************************************************************
5 * (c) 1999-2010 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
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
33 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
36 * [CLASS/FUNCTION INDEX of SCRIPT]
40 * 155: class t3lib_stdGraphic
41 * 236: function init()
43 * SECTION: Layering images / "IMAGE" GIFBUILDER object
44 * 366: function maskImageOntoImage(&$im,$conf,$workArea)
45 * 436: function copyImageOntoImage(&$im,$conf,$workArea)
46 * 458: function copyGifOntoGif(&$im,$cpImg,$conf,$workArea)
47 * 537: function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h)
49 * SECTION: Text / "TEXT" GIFBUILDER object
50 * 587: function makeText(&$im,$conf,$workArea)
51 * 707: function txtPosition($conf,$workArea,$BB)
52 * 761: function calcBBox($conf)
53 * 820: function addToMap($cords,$conf)
54 * 843: function calcTextCordsForMap($cords,$offset, $conf)
55 * 878: function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1)
56 * 915: function fontResize($conf)
57 * 958: function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1)
58 * 1005: function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1)
59 * 1058: function splitString($string,$splitRendering,$fontSize,$fontFile)
60 * 1208: function calcWordSpacing($conf, $scaleFactor=1)
61 * 1227: function getTextScalFactor($conf)
63 * SECTION: Other GIFBUILDER objects related to TEXT
64 * 1262: function makeOutline(&$im,$conf,$workArea,$txtConf)
65 * 1291: function circleOffset($distance, $iterations)
66 * 1315: function makeEmboss(&$im,$conf,$workArea,$txtConf)
67 * 1337: function makeShadow(&$im,$conf,$workArea,$txtConf)
69 * SECTION: Other GIFBUILDER objects
70 * 1469: function makeBox(&$im,$conf,$workArea)
71 * 1491: function makeEffect(&$im, $conf)
72 * 1506: function IMparams($setup)
73 * 1589: function adjust(&$im, $conf)
74 * 1621: function crop(&$im,$conf)
75 * 1652: function scale(&$im,$conf)
76 * 1684: function setWorkArea($workArea)
78 * SECTION: Adjustment functions
79 * 1725: function autolevels(&$im)
80 * 1756: function outputLevels(&$im,$low,$high,$swap='')
81 * 1788: function inputLevels(&$im,$low,$high,$swap='')
82 * 1819: function reduceColors(&$im,$limit, $cols)
83 * 1832: function IMreduceColors($file, $cols)
85 * SECTION: GIFBUILDER Helper functions
86 * 1875: function prependAbsolutePath($fontFile)
87 * 1889: function v5_sharpen($factor)
88 * 1908: function v5_blur($factor)
89 * 1925: function randomName()
90 * 1938: function applyOffset($cords,$OFFSET)
91 * 1951: function convertColor($string)
92 * 2001: function recodeString($string)
93 * 2023: function singleChars($theText,$returnUnicodeNumber=FALSE)
94 * 2046: function objPosition($conf,$workArea,$BB)
96 * SECTION: Scaling, Dimensions of images
97 * 2125: function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0)
98 * 2238: function getImageDimensions($imageFile)
99 * 2266: function cacheImageDimensions($identifyResult)
100 * 2298: function getCachedImageDimensions($imageFile)
101 * 2332: function getImageScale($info,$w,$h,$options)
102 * 2438: function file_exists_typo3temp_file($output,$orig='')
104 * SECTION: ImageMagick API functions
105 * 2499: function imageMagickIdentify($imagefile)
106 * 2534: function imageMagickExec($input,$output,$params)
107 * 2557: function combineExec($input,$overlay,$mask,$output, $handleNegation = false)
108 * 2588: function wrapFileName($inputName)
110 * SECTION: Various IO functions
111 * 2629: function checkFile($file)
112 * 2643: function createTempSubDir($dirName)
113 * 2665: function applyImageMagickToPHPGif(&$im, $command)
114 * 2691: function gif_or_jpg($type,$w,$h)
115 * 2708: function output($file)
116 * 2748: function destroy()
117 * 2758: function imgTag ($imgInfo)
118 * 2770: function ImageWrite($destImg, $theImage)
119 * 2808: function imageGif($destImg, $theImage)
120 * 2820: function imageCreateFromGif($sourceImg)
121 * 2831: function imageCreateFromFile($sourceImg)
122 * 2870: function imagecreate($w, $h)
123 * 2885: function hexColor($col)
124 * 2903: function unifyColors(&$img, $colArr, $closest = false)
126 * TOTAL FUNCTIONS: 66
127 * (This index is automatically created/updated by the extension "extdeveval")
147 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick
148 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
150 * With TYPO3 4.4 GDlib 1.x support was dropped, also an option from config_default.php:
151 * $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.
153 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
156 * @see tslib_gifBuilder
158 class t3lib_stdGraphic
{
160 // Internal configuration, set in init()
161 var $combineScript = 'combine'; // The ImageMagick filename used for combining two images. This name changed during the versions.
162 var $noFramePrepended=0; // If set, there is no frame pointer prepended to the filenames.
163 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())
164 var $imagecopyresized_fix=0; // If set, imagecopyresized will not be called directly. For GD2 (some PHP installs?)
165 var $gifExtension = 'gif'; // This should be changed to 'png' if you want this class to read/make PNG-files instead!
166 var $gdlibExtensions = ''; // File formats supported by gdlib. This variable get's filled in "init" method
167 var $truecolor = TRUE; // Internal variable which get's used to determine wheter GDlib should use function truecolor pendants, @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())
168 var $png_truecolor = false; // Set to true if generated png's should be truecolor by default
169 var $truecolorColors = 0xffffff; // 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
170 var $TTFLocaleConv = ''; // Used to recode input to TTF-functions for other charsets. Deprecated since TYPO3 3.6, will be removed in TYPO3 4.6
171 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.
172 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!
173 var $webImageExt = 'gif,jpg,jpeg,png'; // Commalist of web image extensions (can be shown by a webbrowser)
174 var $maskNegate = ''; // Will be ' -negate' if ImageMagick ver 5.2+. See init();
175 var $NO_IM_EFFECTS = '';
180 'png' => '-colors 64'
182 var $NO_IMAGE_MAGICK = '';
184 var $im_version_4 = 0;
187 // Variables for testing, alternative usage etc.
188 var $filenamePrefix=''; // Filename prefix for images scaled in imageMagickConvert()
189 var $imageMagickConvert_forceFileNameBody=''; // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
190 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.
191 var $dontCompress=0; // Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
192 var $dontUnlinkTempFiles=0; // For debugging ONLY!
193 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...
196 var $IM_commands = Array(); // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
197 var $workArea = Array();
200 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.
201 var $absPrefix = ''; // Prefix for relative paths. Used in "show_item.php" script. Is prefixed the output file name IN imageMagickConvert()
202 var $scalecmd = '-geometry'; // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
203 var $im5fx_blurSteps='1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5'; // Used by v5_blur() to simulate 10 continuous steps of blurring
204 var $im5fx_sharpenSteps='1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5'; // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
205 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
206 var $colMap = Array ( // Array mapping HTML color names to RGB values.
207 'aqua' => Array(0,255,255),
208 'black' => Array(0,0,0),
209 'blue' => Array(0,0,255),
210 'fuchsia' => Array(255,0,255),
211 'gray' => Array(128,128,128),
212 'green' => Array(0,128,0),
213 'lime' => Array(0,255,0),
214 'maroon' => Array(128,0,0),
215 'navy' => Array(0,0,128),
216 'olive' => Array(128,128,0),
217 'purple' => Array(128,0,128),
218 'red' => Array(255,0,0),
219 'silver' => Array(192,192,192),
220 'teal' => Array(0,128,128),
221 'yellow' => Array(255,255,0),
222 'white' => Array(255,255,255)
226 * Charset conversion object:
231 var $nativeCharset=''; // Is set to the native character set of the input strings.
238 * Init function. Must always call this when using the class.
239 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
244 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
246 if (function_exists('imagecreatefromjpeg')&&function_exists('imagejpeg')) {
247 $this->gdlibExtensions
.= ',jpg,jpeg';
249 if (function_exists('imagecreatefrompng')&&function_exists('imagepng')) {
250 $this->gdlibExtensions
.= ',png';
252 if (function_exists('imagecreatefromgif')&&function_exists('imagegif')) {
253 $this->gdlibExtensions
.= ',gif';
255 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['png_truecolor']) {
256 $this->png_truecolor
= true;
258 if (!$gfxConf['im_version_5']) {
259 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.');
260 $this->im_version_4
= true;
261 } elseif ($gfxConf['im_version_5'] === 'im5') {
262 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.');
265 // When GIFBUILDER gets used in truecolor mode
266 // No colors parameter if we generate truecolor images.
267 if ($this->png_truecolor
) {
268 $this->cmds
['png'] = '';
271 // Setting default JPG parameters:
272 $this->jpegQuality
= t3lib_div
::intInRange($gfxConf['jpg_quality'], 10, 100, 75);
273 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -sharpen 50 -quality '.$this->jpegQuality
;
275 if ($gfxConf['im_combine_filename']) $this->combineScript
=$gfxConf['im_combine_filename'];
276 if ($gfxConf['im_noFramePrepended']) $this->noFramePrepended
=1;
278 // kept for backwards compatibility, can be turned on manually through localconf.php,
279 // but not through the installer anymore
280 $this->imagecopyresized_fix
= ($gfxConf['gdlib_2'] === 'no_imagecopyresized_fix' ?
0 : 1);
282 if ($gfxConf['gdlib_png']) {
283 $this->gifExtension
='png';
285 if ($gfxConf['TTFLocaleConv']) {
286 $this->TTFLocaleConv
= $gfxConf['TTFLocaleConv'];
288 if ($gfxConf['enable_typo3temp_db_tracking']) {
289 $this->enable_typo3temp_db_tracking
= $gfxConf['enable_typo3temp_db_tracking'];
292 $this->imageFileExt
= $gfxConf['imagefile_ext'];
294 // This should be set if ImageMagick ver. 5+ is used.
295 if ($gfxConf['im_negate_mask']) {
296 // Boolean. Indicates if the mask images should be inverted first.
297 // This depends of the ImageMagick version. Below ver. 5.1 this should be false.
298 // Above ImageMagick version 5.2+ it should be true.
299 // Just set the flag if the masks works opposite the intension!
300 $this->maskNegate
= ' -negate';
302 if ($gfxConf['im_no_effects']) {
303 // Boolean. This is necessary if using ImageMagick 5+.
304 // Effects in Imagemagick 5+ tends to render very slowly!!
305 // - therefore must be disabled in order not to perform sharpen, blurring and such.
306 $this->NO_IM_EFFECTS
= 1;
308 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -quality '.$this->jpegQuality
;
310 // ... but if 'im_v5effects' is set, don't care about 'im_no_effects'
311 if ($gfxConf['im_v5effects']) {
312 $this->NO_IM_EFFECTS
= 0;
313 $this->V5_EFFECTS
= 1;
315 if ($gfxConf['im_v5effects']>0) {
316 $this->cmds
['jpg'] = $this->cmds
['jpeg'] = '-colorspace RGB -quality '.intval($gfxConf['jpg_quality']).$this->v5_sharpen(10);
320 if (!$gfxConf['im']) {
321 $this->NO_IMAGE_MAGICK
= 1;
323 // Secures that images are not scaled up.
324 if ($gfxConf['im_noScaleUp']) {
328 if (TYPO3_MODE
=='FE') {
329 $this->csConvObj
= $GLOBALS['TSFE']->csConvObj
;
330 } elseif(is_object($GLOBALS['LANG'])) { // BE assumed:
331 $this->csConvObj
= $GLOBALS['LANG']->csConvObj
;
332 } else { // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
333 $this->csConvObj
= t3lib_div
::makeInstance('t3lib_cs');
335 $this->nativeCharset
= $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
353 /*************************************************
355 * Layering images / "IMAGE" GIFBUILDER object
357 *************************************************/
360 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is true.
361 * 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
362 * The operation involves ImageMagick for combining.
364 * @param pointer GDlib image pointer
365 * @param array TypoScript array with configuration for the GIFBUILDER object.
366 * @param array The current working area coordinates.
368 * @see tslib_gifBuilder::make()
370 function maskImageOntoImage(&$im,$conf,$workArea) {
371 if ($conf['file'] && $conf['mask']) {
372 $imgInf = pathinfo($conf['file']);
373 $imgExt = strtolower($imgInf['extension']);
374 if (!t3lib_div
::inList($this->gdlibExtensions
, $imgExt)) {
375 $BBimage = $this->imageMagickConvert($conf['file'],$this->gifExtension
,'','','','','');
377 $BBimage = $this->getImageDimensions($conf['file']);
379 $maskInf = pathinfo($conf['mask']);
380 $maskExt = strtolower($maskInf['extension']);
381 if (!t3lib_div
::inList($this->gdlibExtensions
, $maskExt)) {
382 $BBmask = $this->imageMagickConvert($conf['mask'],$this->gifExtension
,'','','','','');
384 $BBmask = $this->getImageDimensions($conf['mask']);
386 if ($BBimage && $BBmask) {
389 $tmpStr = $this->randomName();
390 $theImage = $tmpStr.'_img.'.$this->gifExtension
;
391 $theDest = $tmpStr.'_dest.'.$this->gifExtension
;
392 $theMask = $tmpStr.'_mask.'.$this->gifExtension
;
393 // prepare overlay image
394 $cpImg = $this->imageCreateFromFile($BBimage[3]);
395 $destImg = imagecreatetruecolor($w, $h);
396 $Bcolor = ImageColorAllocate($destImg, 0,0,0);
397 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
398 $this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
399 $this->ImageWrite($destImg, $theImage);
400 imageDestroy($cpImg);
401 imageDestroy($destImg);
402 // prepare mask image
403 $cpImg = $this->imageCreateFromFile($BBmask[3]);
404 $destImg = imagecreatetruecolor($w, $h);
405 $Bcolor = ImageColorAllocate($destImg, 0, 0, 0);
406 ImageFilledRectangle($destImg, 0, 0, $w, $h, $Bcolor);
407 $this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
408 $this->ImageWrite($destImg, $theMask);
409 imageDestroy($cpImg);
410 imageDestroy($destImg);
412 $this->ImageWrite($im, $theDest);
414 $this->combineExec($theDest,$theImage,$theMask,$theDest, true); // Let combineExec handle maskNegation
416 $backIm = $this->imageCreateFromFile($theDest); // The main image is loaded again...
417 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
418 ImageColorTransparent($backIm,-1);
421 // unlink files from process
422 if (!$this->dontUnlinkTempFiles
) {
432 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is false (using only $conf['file'])
434 * @param pointer GDlib image pointer
435 * @param array TypoScript array with configuration for the GIFBUILDER object.
436 * @param array The current working area coordinates.
438 * @see tslib_gifBuilder::make(), maskImageOntoImage()
440 function copyImageOntoImage(&$im,$conf,$workArea) {
442 if (!t3lib_div
::inList($this->gdlibExtensions
, $conf['BBOX'][2])) {
443 $conf['BBOX']=$this->imageMagickConvert($conf['BBOX'][3],$this->gifExtension
,'','','','','');
444 $conf['file']=$conf['BBOX'][3];
446 $cpImg = $this->imageCreateFromFile($conf['file']);
447 $this->copyGifOntoGif($im,$cpImg,$conf,$workArea);
448 imageDestroy($cpImg);
453 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
455 * @param pointer GDlib image pointer, destination (bottom image)
456 * @param pointer GDlib image pointer, source (top image)
457 * @param array TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
458 * @param array Work area
459 * @return void Works on the $im image pointer
462 function copyGifOntoGif(&$im,$cpImg,$conf,$workArea) {
463 $cpW = imagesx($cpImg);
464 $cpH = imagesy($cpImg);
465 $tile = t3lib_div
::intExplode(',',$conf['tile']);
466 $tile[0] = t3lib_div
::intInRange($tile[0],1,20);
467 $tile[1] = t3lib_div
::intInRange($tile[1],1,20);
468 $cpOff = $this->objPosition($conf,$workArea,Array($cpW*$tile[0],$cpH*$tile[1]));
470 for ($xt=0;$xt<$tile[0];$xt++
) {
471 $Xstart=$cpOff[0]+
$cpW*$xt;
472 if ($Xstart+
$cpW > $workArea[0]) { // if this image is inside of the workArea, then go on
474 if ($Xstart < $workArea[0]) {
475 $cpImgCutX = $workArea[0]-$Xstart;
476 $Xstart = $workArea[0];
480 $w = $cpW-$cpImgCutX;
481 if ($Xstart > $workArea[0]+
$workArea[2]-$w) {
482 $w = $workArea[0]+
$workArea[2]-$Xstart;
484 if ($Xstart < $workArea[0]+
$workArea[2]) { // if this image is inside of the workArea, then go on
486 for ($yt=0;$yt<$tile[1];$yt++
) {
487 $Ystart=$cpOff[1]+
$cpH*$yt;
488 if ($Ystart+
$cpH > $workArea[1]) { // if this image is inside of the workArea, then go on
489 if ($Ystart < $workArea[1]) {
490 $cpImgCutY = $workArea[1]-$Ystart;
491 $Ystart = $workArea[1];
495 $h = $cpH-$cpImgCutY;
496 if ($Ystart > $workArea[1]+
$workArea[3]-$h) {
497 $h = $workArea[1]+
$workArea[3]-$Ystart;
499 if ($Ystart < $workArea[1]+
$workArea[3]) { // if this image is inside of the workArea, then go on
500 $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
510 * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
512 * OK, the reason for this stupid fix is the following story:
513 * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
514 * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
515 * copy a color-ful image onto the destination.
517 * 1) Create a blank TRUE-COLOR image
518 * 2) Copy the destination image onto that one
519 * 3) Then do the actual operation; Copying the source (top image) onto that
520 * 4) ... and return the result pointer.
521 * 5) Reduce colors (if we do not, the result may become strange!)
522 * It works, but the resulting images is now a true-color PNG which may be very large.
523 * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
525 * For parameters, see PHP function "imagecopyresized()"
527 * @param pointer see PHP function "imagecopyresized()"
528 * @param pointer see PHP function "imagecopyresized()"
529 * @param integer see PHP function "imagecopyresized()"
530 * @param integer see PHP function "imagecopyresized()"
531 * @param integer see PHP function "imagecopyresized()"
532 * @param integer see PHP function "imagecopyresized()"
533 * @param integer see PHP function "imagecopyresized()"
534 * @param integer see PHP function "imagecopyresized()"
535 * @param integer see PHP function "imagecopyresized()"
536 * @param integer see PHP function "imagecopyresized()"
539 * @see t3lib_iconWorks::imagecopyresized()
541 function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h) {
542 if ($this->imagecopyresized_fix
) {
543 $im_base = imagecreatetruecolor(imagesx($im), imagesy($im)); // Make true color image
544 imagecopyresized($im_base, $im, 0,0,0,0, imagesx($im),imagesy($im),imagesx($im),imagesy($im)); // Copy the source image onto that
545 imagecopyresized($im_base, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h); // Then copy the $cpImg onto that (the actual operation!)
546 $im = $im_base; // Set pointer
547 if (!$this->truecolor
) {
548 $this->makeEffect($im, Array('value'=>'colors='.t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256))); // Reduce to "reduceColors" colors - make SURE that IM is working then!
551 imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
576 /********************************
578 * Text / "TEXT" GIFBUILDER object
580 ********************************/
583 * Implements the "TEXT" GIFBUILDER object
585 * @param pointer GDlib image pointer
586 * @param array TypoScript array with configuration for the GIFBUILDER object.
587 * @param array The current working area coordinates.
589 * @see tslib_gifBuilder::make()
591 function makeText(&$im,$conf,$workArea) {
593 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf);
595 $txtPos = $this->txtPosition($conf,$workArea,$conf['BBOX']);
596 $theText = $this->recodeString($conf['text']);
598 if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
599 $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2],$txtPos, $conf['imgMap.']), $conf['imgMap.']);
601 if (!$conf['hideButCreateMap']) {
603 $cols=$this->convertColor($conf['fontColor']);
604 // NiceText is calculated
605 if (!$conf['niceText']) {
606 // Font Color is reserved:
607 if (!$this->truecolor
) {
608 $reduce = t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256);
609 $this->reduceColors($im, $reduce-49, $reduce-50); // If "reduce-49" colors (or more) are used reduce them to "reduce-50"
611 $Fcolor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
612 // antiAliasing is setup:
613 $Fcolor = ($conf['antiAlias']) ?
$Fcolor : -$Fcolor;
615 for ($a=0; $a<$conf['iterations']; $a++
) {
616 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
617 $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic
::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.']);
619 $this->renderTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf);
622 } else { // NICETEXT::
623 // options anti_aliased and iterations is NOT available when doing this!!
626 $tmpStr = $this->randomName();
628 $fileMenu = $tmpStr.'_menuNT.'.$this->gifExtension
;
629 $fileColor = $tmpStr.'_colorNT.'.$this->gifExtension
;
630 $fileMask = $tmpStr.'_maskNT.'.$this->gifExtension
;
632 $sF = t3lib_div
::intInRange($conf['niceText.']['scaleFactor'],2,5);
633 $newW = ceil($sF*imagesx($im));
634 $newH = ceil($sF*imagesy($im));
637 $maskImg = imagecreatetruecolor($newW, $newH);
638 $Bcolor = ImageColorAllocate($maskImg, 255,255,255);
639 ImageFilledRectangle($maskImg, 0, 0, $newW, $newH, $Bcolor);
640 $Fcolor = ImageColorAllocate($maskImg, 0,0,0);
641 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
642 $this->SpacedImageTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic
::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing, $conf['splitRendering.'],$sF);
644 $this->renderTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf, $sF);
646 $this->ImageWrite($maskImg, $fileMask);
647 ImageDestroy($maskImg);
649 // Downscales the mask
650 if ($this->NO_IM_EFFECTS
) {
651 if ($this->maskNegate
) {
652 $command = trim($this->scalecmd
.' '.$w.'x'.$h.'!'); // Negate 2 times makes no negate...
654 $command = trim($this->scalecmd
.' '.$w.'x'.$h.'! -negate');
657 if ($this->maskNegate
) {
658 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd
.' '.$w.'x'.$h.'! '.$conf['niceText.']['after']);
660 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd
.' '.$w.'x'.$h.'! '.$conf['niceText.']['after'].' -negate');
662 if ($conf['niceText.']['sharpen']) {
663 if ($this->V5_EFFECTS
) {
664 $command.=$this->v5_sharpen($conf['niceText.']['sharpen']);
666 $command.=' -sharpen '.t3lib_div
::intInRange($conf['niceText.']['sharpen'],1,99);
671 $this->imageMagickExec($fileMask,$fileMask,$command);
673 // Make the color-file
674 $colorImg = imagecreatetruecolor($w, $h);
675 $Ccolor = ImageColorAllocate($colorImg, $cols[0],$cols[1],$cols[2]);
676 ImageFilledRectangle($colorImg, 0, 0, $w, $h, $Ccolor);
677 $this->ImageWrite($colorImg, $fileColor);
678 ImageDestroy($colorImg);
680 // The mask is applied
681 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
683 $this->combineExec($fileMenu,$fileColor,$fileMask, $fileMenu);
685 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
686 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
687 ImageColorTransparent($backIm,-1);
691 // Deleting temporary files;
692 if (!$this->dontUnlinkTempFiles
) {
702 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
704 * @param array TypoScript array for the TEXT GIFBUILDER object
705 * @param array Workarea definition
706 * @param array Bounding box information, was set in tslib_gifBuilder::start()
707 * @return array [0]=x, [1]=y, [2]=w, [3]=h
711 function txtPosition($conf,$workArea,$BB) {
713 $angle=intval($conf['angle'])/180*pi();
715 $straightBB = $this->calcBBox($conf);
717 // offset, align, valign, workarea
718 $result=Array(); // [0]=x, [1]=y, [2]=w, [3]=h
724 switch($conf['align']) {
727 $factor=abs(cos($angle));
728 $sign=(cos($angle)<0)?
-1:1;
729 $len1 = $sign*$factor*$straightBB[0];
731 $result[0] = $w-ceil($len2*$factor+
(1-$factor)*$len1);
733 $factor=abs(sin($angle));
734 $sign=(sin($angle)<0)?
-1:1;
735 $len1= $sign*$factor*$straightBB[0];
737 $result[1]=ceil($len2*$factor+
(1-$factor)*$len1);
740 switch($conf['align']) {
744 $result[0] = round(($result[0])/2);
745 $result[1] = round(($result[1])/2);
752 $result = $this->applyOffset($result,t3lib_div
::intExplode(',',$conf['offset']));
753 $result = $this->applyOffset($result,$workArea);
758 * Calculates bounding box information for the TEXT GIFBUILDER object.
760 * @param array TypoScript array for the TEXT GIFBUILDER object
761 * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
763 * @see txtPosition(), tslib_gifBuilder::start()
765 function calcBBox($conf) {
766 $sF = $this->getTextScalFactor($conf);
767 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf, $sF);
768 $theText = $this->recodeString($conf['text']);
770 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $theText, $conf['splitRendering.'],$sF);
771 $theBBoxInfo = $charInf;
772 if ($conf['angle']) {
773 $xArr = Array($charInf[0],$charInf[2],$charInf[4],$charInf[6]);
774 $yArr = Array($charInf[1],$charInf[3],$charInf[5],$charInf[7]);
775 $x=max($xArr)-min($xArr);
776 $y=max($yArr)-min($yArr);
778 $x = ($charInf[2]-$charInf[0]);
779 $y = ($charInf[1]-$charInf[7]);
781 // Set original lineHeight (used by line breaks):
782 $theBBoxInfo['lineHeight'] = $y;
784 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
786 if (!$spacing && $wordSpacing) {
787 $bits = explode(' ',$theText);
788 foreach ($bits as $word) {
790 $wordInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $word, $conf['splitRendering.'],$sF);
791 $wordW = ($wordInf[2]-$wordInf[0]);
792 $x+
=$wordW+
$wordSpacing;
795 $utf8Chars = $this->singleChars($theText);
796 // For each UTF-8 char, do:
797 foreach($utf8Chars as $char) {
798 $charInf = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $char, $conf['splitRendering.'],$sF);
799 $charW = ($charInf[2]-$charInf[0]);
800 $x+
=$charW+
(($char==' ')?
$wordSpacing:$spacing);
803 } elseif (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($conf['text'], $conf) > $conf['breakWidth']) {
806 $breakWidth = $conf['breakWidth'];
807 $breakSpace = $this->getBreakSpace($conf, $theBBoxInfo);
809 $wordPairs = $this->getWordPairsForLineBreak($conf['text']);
810 // Iterate through all word pairs:
811 foreach ($wordPairs as $index => $wordPair) {
812 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
813 if ($index == 0 ||
$currentWidth +
$wordWidth <= $breakWidth) {
814 $currentWidth+
= $wordWidth;
816 $maxWidth = max($maxWidth, $currentWidth);
819 $currentWidth = $wordWidth;
822 $x = max($maxWidth, $currentWidth) * $sF;
828 if (is_array($theBBoxInfo)) {
829 foreach ($theBBoxInfo as &$value) {
830 $value = ceil($value / $sF);
834 return array($x, $y, $theBBoxInfo);
838 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
840 * @param array Coordinates for a polygon image map as created by ->calcTextCordsForMap()
841 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
844 * @see makeText(), calcTextCordsForMap()
846 function addToMap($cords,$conf) {
847 $JS = $conf['noBlur'] ?
'' : ' onfocus="blurLink(this);"';
851 ' coords="'.implode(',',$cords).'"'.
852 ' href="'.htmlspecialchars($conf['url']).'"'.
853 ($conf['target'] ?
' target="'.htmlspecialchars($conf['target']).'"' : '').
855 (strlen($conf['titleText']) ?
' title="'.htmlspecialchars($conf['titleText']).'"' : '').
856 ' alt="'.htmlspecialchars($conf['altText']).'" />';
860 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
862 * @param array Coordinates (from BBOX array)
863 * @param array Offset array
864 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
867 * @see makeText(), calcTextCordsForMap()
869 function calcTextCordsForMap($cords,$offset, $conf) {
870 $pars = t3lib_div
::intExplode(',',$conf['explode'].',');
872 $newCords[0] = $cords[0]+
$offset[0]-$pars[0];
873 $newCords[1] = $cords[1]+
$offset[1]+
$pars[1];
874 $newCords[2] = $cords[2]+
$offset[0]+
$pars[0];
875 $newCords[3] = $cords[3]+
$offset[1]+
$pars[1];
876 $newCords[4] = $cords[4]+
$offset[0]+
$pars[0];
877 $newCords[5] = $cords[5]+
$offset[1]-$pars[1];
878 $newCords[6] = $cords[6]+
$offset[0]-$pars[0];
879 $newCords[7] = $cords[7]+
$offset[1]-$pars[1];
885 * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
886 * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
889 * @param pointer (See argument for PHP function imageTTFtext())
890 * @param integer (See argument for PHP function imageTTFtext())
891 * @param integer (See argument for PHP function imageTTFtext())
892 * @param integer (See argument for PHP function imageTTFtext())
893 * @param integer (See argument for PHP function imageTTFtext())
894 * @param integer (See argument for PHP function imageTTFtext())
895 * @param string (See argument for PHP function imageTTFtext())
896 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
897 * @param integer The spacing of letters in pixels
898 * @param integer The spacing of words in pixels
899 * @param array $splitRenderingConf array
900 * @param integer Scale factor
904 function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1) {
909 if (!$spacing && $wordSpacing) {
910 $bits = explode(' ',$text);
911 foreach ($bits as $word) {
913 $wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf ,$sF);
914 $wordW = ($wordInf[2]-$wordInf[0]);
915 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
916 $x+
=$wordW+
$wordSpacing;
919 $utf8Chars = $this->singleChars($text);
920 // For each UTF-8 char, do:
921 foreach($utf8Chars as $char) {
922 $charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
923 $charW = ($charInf[2]-$charInf[0]);
924 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
925 $x+
=$charW+
(($char==' ')?
$wordSpacing:$spacing);
931 * Function that finds the right fontsize that will render the textstring within a certain width
933 * @param array The TypoScript properties of the TEXT GIFBUILDER object
934 * @return integer The new fontSize
936 * @author René Fritz <r.fritz@colorcube.de>
937 * @see tslib_gifBuilder::start()
939 function fontResize($conf) {
940 // 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!!!!
941 $maxWidth = intval($conf['maxWidth']);
942 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf);
944 if ($spacing ||
$wordSpacing) { // If any kind of spacing applys, we use this function:
945 return $conf['fontSize'];
946 // ################ no calc for spacing yet !!!!!!
949 // determine bounding box.
950 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($conf['text']), $conf['splitRendering.']);
951 if ($conf['angle']< 0) {
952 $pixelWidth = abs($bounds[4]-$bounds[0]);
953 } elseif ($conf['angle'] > 0) {
954 $pixelWidth = abs($bounds[2]-$bounds[6]);
956 $pixelWidth = abs($bounds[4]-$bounds[6]);
959 // Size is fine, exit:
960 if ($pixelWidth <= $maxWidth) {
965 } while ($conf['fontSize']>1);
968 return $conf['fontSize'];
972 * Wrapper for ImageTTFBBox
974 * @param integer (See argument for PHP function ImageTTFBBox())
975 * @param integer (See argument for PHP function ImageTTFBBox())
976 * @param string (See argument for PHP function ImageTTFBBox())
977 * @param string (See argument for PHP function ImageTTFBBox())
978 * @param array Split-rendering configuration
979 * @param integer Scale factor
980 * @return array Information array.
982 function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1) {
985 $offsetInfo = array();
986 $stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
988 // Traverse string parts:
989 foreach($stringParts as $strCfg) {
990 $fontFile = t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']);
991 if (is_readable($fontFile)) {
993 // Calculate Bounding Box for part:
994 $calc = ImageTTFBBox(t3lib_div
::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);
996 // Calculate offsets:
997 if (!count($offsetInfo)) {
998 $offsetInfo = $calc; // First run, just copy over.
1000 $offsetInfo[2]+
=$calc[2]-$calc[0]+
intval($splitRendering['compX'])+
intval($strCfg['xSpaceBefore'])+
intval($strCfg['xSpaceAfter']);
1001 $offsetInfo[3]+
=$calc[3]-$calc[1]-intval($splitRendering['compY'])-intval($strCfg['ySpaceBefore'])-intval($strCfg['ySpaceAfter']);
1002 $offsetInfo[4]+
=$calc[4]-$calc[6]+
intval($splitRendering['compX'])+
intval($strCfg['xSpaceBefore'])+
intval($strCfg['xSpaceAfter']);
1003 $offsetInfo[5]+
=$calc[5]-$calc[7]-intval($splitRendering['compY'])-intval($strCfg['ySpaceBefore'])-intval($strCfg['ySpaceAfter']);
1007 debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFBBoxWrapper()');
1015 * Wrapper for ImageTTFText
1017 * @param pointer (See argument for PHP function imageTTFtext())
1018 * @param integer (See argument for PHP function imageTTFtext())
1019 * @param integer (See argument for PHP function imageTTFtext())
1020 * @param integer (See argument for PHP function imageTTFtext())
1021 * @param integer (See argument for PHP function imageTTFtext())
1022 * @param integer (See argument for PHP function imageTTFtext())
1023 * @param string (See argument for PHP function imageTTFtext())
1024 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1025 * @param array Split-rendering configuration
1026 * @param integer Scale factor
1029 function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1) {
1032 $stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
1036 // Traverse string parts:
1037 foreach($stringParts as $i => $strCfg) {
1040 $colorIndex = $color;
1042 // Set custom color if any (only when niceText is off):
1043 if ($strCfg['color'] && $sF==1) {
1044 $cols = $this->convertColor($strCfg['color']);
1045 $colorIndex = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
1046 $colorIndex = $color >= 0 ?
$colorIndex : -$colorIndex;
1049 // Setting xSpaceBefore
1051 $x+
= intval($strCfg['xSpaceBefore']);
1052 $y-= intval($strCfg['ySpaceBefore']);
1055 $fontFile = t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']);
1056 if (is_readable($fontFile)) {
1059 ImageTTFText($im, t3lib_div
::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
1061 // Calculate offset to apply:
1062 $wordInf = ImageTTFBBox(t3lib_div
::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, t3lib_stdGraphic
::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']);
1063 $x+
= $wordInf[2]-$wordInf[0]+
intval($splitRendering['compX'])+
intval($strCfg['xSpaceAfter']);
1064 $y+
= $wordInf[5]-$wordInf[7]-intval($splitRendering['compY'])-intval($strCfg['ySpaceAfter']);
1067 debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFTextWrapper()');
1074 * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
1076 * @param string UTF-8 string
1077 * @param array Split-rendering configuration from GIFBUILDER TEXT object.
1078 * @param integer Current fontsize
1079 * @param string Current font file
1080 * @return array Array with input string splitted according to configuration
1082 function splitString($string,$splitRendering,$fontSize,$fontFile) {
1084 // Initialize by setting the whole string and default configuration as the first entry.
1088 'fontSize' => $fontSize,
1089 'fontFile' => $fontFile
1092 // Traverse the split-rendering configuration:
1093 // Splitting will create more entries in $result with individual configurations.
1094 if (is_array($splitRendering)) {
1095 $sKeyArray = t3lib_TStemplate
::sortedKeyList($splitRendering);
1097 // Traverse configured options:
1098 foreach($sKeyArray as $key) {
1099 $cfg = $splitRendering[$key.'.'];
1101 // Process each type of split rendering keyword:
1102 switch((string)$splitRendering[$key]) {
1103 case 'highlightWord':
1104 if (strlen($cfg['value'])) {
1105 $newResult = array();
1107 // Traverse the current parts of the result array:
1108 foreach($result as $part) {
1109 // Explode the string value by the word value to highlight:
1110 $explodedParts = explode($cfg['value'],$part['str']);
1111 foreach($explodedParts as $c => $expValue) {
1112 if (strlen($expValue)) {
1113 $newResult[] = array_merge($part,array('str' => $expValue));
1115 if ($c+
1 < count($explodedParts)) {
1116 $newResult[] = array(
1117 'str' => $cfg['value'],
1118 'fontSize' => $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1119 'fontFile' => $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1120 'color' => $cfg['color'],
1121 'xSpaceBefore' => $cfg['xSpaceBefore'],
1122 'xSpaceAfter' => $cfg['xSpaceAfter'],
1123 'ySpaceBefore' => $cfg['ySpaceBefore'],
1124 'ySpaceAfter' => $cfg['ySpaceAfter'],
1130 // Set the new result as result array:
1131 if (count($newResult)) {
1132 $result = $newResult;
1137 if (strlen($cfg['value'])) {
1139 // Initialize range:
1140 $ranges = t3lib_div
::trimExplode(',',$cfg['value'],1);
1141 foreach($ranges as $i => $rangeDef) {
1142 $ranges[$i] = t3lib_div
::intExplode('-',$ranges[$i]);
1143 if (!isset($ranges[$i][1])) $ranges[$i][1] = $ranges[$i][0];
1145 $newResult = array();
1147 // Traverse the current parts of the result array:
1148 foreach($result as $part) {
1154 // Explode the string value by the word value to highlight:
1155 $utf8Chars = $this->singleChars($part['str']);
1156 foreach($utf8Chars as $utfChar) {
1158 // Find number and evaluate position:
1159 $uNumber = $this->csConvObj
->utf8CharToUnumber($utfChar);
1161 foreach($ranges as $rangeDef) {
1162 if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] ||
$uNumber <= $rangeDef[1])) {
1167 if ($currentState==-1) $currentState = $inRange; // Initialize first char
1170 if ($inRange != $currentState && !t3lib_div
::inList('32,10,13,9',$uNumber)) {
1173 if (strlen($bankAccum)) {
1174 $newResult[] = array(
1175 'str' => $bankAccum,
1176 'fontSize' => $currentState && $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1177 'fontFile' => $currentState && $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1178 'color' => $currentState ?
$cfg['color'] : '',
1179 'xSpaceBefore' => $currentState ?
$cfg['xSpaceBefore'] : '',
1180 'xSpaceAfter' => $currentState ?
$cfg['xSpaceAfter'] : '',
1181 'ySpaceBefore' => $currentState ?
$cfg['ySpaceBefore'] : '',
1182 'ySpaceAfter' => $currentState ?
$cfg['ySpaceAfter'] : '',
1186 // Initialize new settings:
1187 $currentState = $inRange;
1191 // Add char to bank:
1192 $bankAccum.=$utfChar;
1195 // Set result for FINAL part:
1196 if (strlen($bankAccum)) {
1197 $newResult[] = array(
1198 'str' => $bankAccum,
1199 'fontSize' => $currentState && $cfg['fontSize'] ?
$cfg['fontSize'] : $part['fontSize'],
1200 'fontFile' => $currentState && $cfg['fontFile'] ?
$cfg['fontFile'] : $part['fontFile'],
1201 'color' => $currentState ?
$cfg['color'] : '',
1202 'xSpaceBefore' => $currentState ?
$cfg['xSpaceBefore'] : '',
1203 'xSpaceAfter' => $currentState ?
$cfg['xSpaceAfter'] : '',
1204 'ySpaceBefore' => $currentState ?
$cfg['ySpaceBefore'] : '',
1205 'ySpaceAfter' => $currentState ?
$cfg['ySpaceAfter'] : '',
1210 // Set the new result as result array:
1211 if (count($newResult)) {
1212 $result = $newResult;
1224 * Calculates the spacing and wordSpacing values
1226 * @param array TypoScript array for the TEXT GIFBUILDER object
1227 * @param integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1228 * @return array Array with two keys [0]/[1] being array($spacing,$wordSpacing)
1232 function calcWordSpacing($conf, $scaleFactor=1) {
1234 $spacing = intval($conf['spacing']);
1235 $wordSpacing = intval($conf['wordSpacing']);
1236 $wordSpacing = $wordSpacing?
$wordSpacing:$spacing*2;
1238 $spacing*=$scaleFactor;
1239 $wordSpacing*=$scaleFactor;
1241 return array($spacing,$wordSpacing);
1245 * Calculates and returns the niceText.scaleFactor
1247 * @param array TypoScript array for the TEXT GIFBUILDER object
1248 * @return integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1251 function getTextScalFactor($conf) {
1252 if (!$conf['niceText']) {
1254 } else { // NICETEXT::
1255 $sF = t3lib_div
::intInRange($conf['niceText.']['scaleFactor'],2,5);
1261 * Renders a regular text and takes care of a possible line break automatically.
1263 * @param pointer (See argument for PHP function imageTTFtext())
1264 * @param integer (See argument for PHP function imageTTFtext())
1265 * @param integer (See argument for PHP function imageTTFtext())
1266 * @param integer (See argument for PHP function imageTTFtext())
1267 * @param integer (See argument for PHP function imageTTFtext())
1268 * @param integer (See argument for PHP function imageTTFtext())
1269 * @param string (See argument for PHP function imageTTFtext())
1270 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1271 * @param array Split-rendering configuration
1272 * @param integer Scale factor
1273 * @param array $conf: The configuration
1276 protected function renderTTFText(&$im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $conf, $sF = 1) {
1277 if (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($string, $conf) > $conf['breakWidth']) {
1281 $breakWidth = $conf['breakWidth'];
1282 $breakSpace = $this->getBreakSpace($conf);
1284 $wordPairs = $this->getWordPairsForLineBreak($string);
1285 // Iterate through all word pairs:
1286 foreach ($wordPairs as $index => $wordPair) {
1287 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
1288 if ($index == 0 ||
$currentWidth +
$wordWidth <= $breakWidth) {
1289 $currentWidth+
= $wordWidth;
1290 $phrase.= $wordPair;
1292 // Render the current phrase that is below breakWidth:
1293 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1294 // Calculate the news height offset:
1296 // Restart the phrase:
1297 $currentWidth = $wordWidth;
1298 $phrase = $wordPair;
1301 // Render the remaining phrase:
1302 if ($currentWidth) {
1303 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1306 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
1311 * Gets the word pairs used for automatic line breaks.
1313 * @param string $string
1316 protected function getWordPairsForLineBreak($string) {
1317 $wordPairs = array();
1319 $wordsArray = preg_split('#([- .,!:]+)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE
);
1320 $wordsCount = count($wordsArray);
1321 for ($index=0; $index < $wordsCount; $index+
= 2) {
1322 $wordPairs[] = $wordsArray[$index] . $wordsArray[$index +
1];
1329 * Gets the rendered text width.
1331 * @param string $text
1332 * @param array $conf
1335 protected function getRenderedTextWidth($text, $conf) {
1336 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($text), $conf['splitRendering.']);
1337 if ($conf['angle']< 0) {
1338 $pixelWidth = abs($bounds[4]-$bounds[0]);
1339 } elseif ($conf['angle'] > 0) {
1340 $pixelWidth = abs($bounds[2]-$bounds[6]);
1342 $pixelWidth = abs($bounds[4]-$bounds[6]);
1348 * Gets the break space for each new line.
1350 * @param array $conf: TypoScript configuration for the currently rendered object
1351 * @param array $boundingBox: The bounding box the the currently rendered object
1352 * @return integer The break space
1354 protected function getBreakSpace($conf, array $boundingBox = NULL) {
1355 if (!isset($boundingBox)) {
1356 $boundingBox = $this->calcBBox($conf);
1357 $boundingBox = $boundingBox[2];
1360 if (isset($conf['breakSpace']) && $conf['breakSpace']) {
1361 $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
1363 $breakSpace = $boundingBox['lineHeight'];
1379 /*********************************************
1381 * Other GIFBUILDER objects related to TEXT
1383 *********************************************/
1386 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
1388 * @param pointer GDlib image pointer
1389 * @param array TypoScript array with configuration for the GIFBUILDER object.
1390 * @param array The current working area coordinates.
1391 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1393 * @see tslib_gifBuilder::make(), makeText()
1395 function makeOutline(&$im,$conf,$workArea,$txtConf) {
1396 $thickness = intval($conf['thickness']);
1398 $txtConf['fontColor'] = $conf['color'];
1399 $outLineDist = t3lib_div
::intInRange($thickness,1,2);
1400 for ($b=1;$b<=$outLineDist;$b++
) {
1406 $outL = $this->circleOffset($b, $it);
1407 for ($a=0;$a<$it;$a++
) {
1408 $this->makeText($im,$txtConf,$this->applyOffset($workArea,$outL[$a]));
1415 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
1419 * @param integer Distance
1420 * @param integer Iterations.
1422 * @see makeOutline()
1424 function circleOffset($distance, $iterations) {
1426 if ($distance && $iterations) {
1427 for ($a=0;$a<$iterations;$a++
) {
1428 $yOff = round(sin(2*pi()/$iterations*($a+
1))*100*$distance);
1429 if ($yOff) {$yOff = intval(ceil(abs($yOff/100))*($yOff/abs($yOff)));}
1430 $xOff = round(cos(2*pi()/$iterations*($a+
1))*100*$distance);
1431 if ($xOff) {$xOff = intval(ceil(abs($xOff/100))*($xOff/abs($xOff)));}
1432 $res[$a] = Array($xOff,$yOff);
1439 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
1441 * @param pointer GDlib image pointer
1442 * @param array TypoScript array with configuration for the GIFBUILDER object.
1443 * @param array The current working area coordinates.
1444 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1446 * @see tslib_gifBuilder::make(), makeShadow()
1448 function makeEmboss(&$im,$conf,$workArea,$txtConf) {
1449 $conf['color']=$conf['highColor'];
1450 $this->makeShadow($im,$conf,$workArea,$txtConf);
1451 $newOffset = t3lib_div
::intExplode(',',$conf['offset']);
1454 $conf['offset']=implode(',',$newOffset);
1455 $conf['color']=$conf['lowColor'];
1456 $this->makeShadow($im,$conf,$workArea,$txtConf);
1460 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
1461 * The operation involves ImageMagick for combining.
1463 * @param pointer GDlib image pointer
1464 * @param array TypoScript array with configuration for the GIFBUILDER object.
1465 * @param array The current working area coordinates.
1466 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1468 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
1470 function makeShadow(&$im,$conf,$workArea,$txtConf) {
1471 $workArea = $this->applyOffset($workArea,t3lib_div
::intExplode(',',$conf['offset']));
1472 $blurRate = t3lib_div
::intInRange(intval($conf['blur']),0,99);
1474 if (!$blurRate ||
$this->NO_IM_EFFECTS
) { // No effects if ImageMagick ver. 5+
1475 $txtConf['fontColor'] = $conf['color'];
1476 $this->makeText($im,$txtConf,$workArea);
1480 $blurBorder= 3; // area around the blur used for cropping something
1481 $tmpStr = $this->randomName();
1482 $fileMenu = $tmpStr.'_menu.'.$this->gifExtension
;
1483 $fileColor = $tmpStr.'_color.'.$this->gifExtension
;
1484 $fileMask = $tmpStr.'_mask.'.$this->gifExtension
;
1486 // BlurColor Image laves
1487 $blurColImg = imagecreatetruecolor($w, $h);
1488 $bcols=$this->convertColor($conf['color']);
1489 $Bcolor = ImageColorAllocate($blurColImg, $bcols[0],$bcols[1],$bcols[2]);
1490 ImageFilledRectangle($blurColImg, 0, 0, $w, $h, $Bcolor);
1491 $this->ImageWrite($blurColImg, $fileColor);
1492 ImageDestroy($blurColImg);
1494 // The mask is made: BlurTextImage
1495 $blurTextImg = imagecreatetruecolor($w +
$blurBorder * 2, $h +
$blurBorder * 2);
1496 $Bcolor = ImageColorAllocate($blurTextImg, 0,0,0); // black background
1497 ImageFilledRectangle($blurTextImg, 0, 0, $w+
$blurBorder*2, $h+
$blurBorder*2, $Bcolor);
1498 $txtConf['fontColor'] = 'white';
1499 $blurBordArr = Array($blurBorder,$blurBorder);
1500 $this->makeText($blurTextImg,$txtConf, $this->applyOffset($workArea,$blurBordArr));
1501 $this->ImageWrite($blurTextImg, $fileMask); // dump to temporary file
1502 ImageDestroy($blurTextImg); // destroy
1506 $command.=$this->maskNegate
;
1508 if ($this->V5_EFFECTS
) {
1509 $command.=$this->v5_blur($blurRate+
1);
1511 // Blurring of the mask
1512 $times = ceil($blurRate/10); // How many blur-commands that is executed. Min = 1;
1513 $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.
1514 $newBlurRate = t3lib_div
::intInRange($newBlurRate,1,99);
1515 for ($a=0;$a<$times;$a++
) { // Building blur-command
1516 $command.=' -blur '.$blurRate;
1520 $this->imageMagickExec($fileMask,$fileMask,$command.' +matte');
1522 $blurTextImg_tmp = $this->imageCreateFromFile($fileMask); // the mask is loaded again
1523 if ($blurTextImg_tmp) { // if nothing went wrong we continue with the blurred mask
1525 // cropping the border from the mask
1526 $blurTextImg = imagecreatetruecolor($w, $h);
1527 $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
1528 ImageDestroy($blurTextImg_tmp); // Destroy the temporary mask
1532 if ($conf['intensity']) {
1533 $intensity = t3lib_div
::intInRange($conf['intensity'],0,100);
1535 $intensity = ceil(255-($intensity/100*255));
1536 $this->inputLevels($blurTextImg,0,$intensity,$this->maskNegate
);
1538 $opacity = t3lib_div
::intInRange(intval($conf['opacity']),0,100);
1539 if ($opacity && $opacity<100) {
1540 $high = ceil(255*$opacity/100);
1541 $this->outputLevels($blurTextImg,0,$high,$this->maskNegate
); // reducing levels as the opacity demands
1544 $this->ImageWrite($blurTextImg, $fileMask); // Dump the mask again
1545 ImageDestroy($blurTextImg); // Destroy the mask
1547 // The pictures are combined
1548 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
1550 $this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);
1552 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
1553 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
1554 ImageColorTransparent($backIm,-1);
1558 // Deleting temporary files;
1559 if (!$this->dontUnlinkTempFiles
) {
1587 /****************************
1589 * Other GIFBUILDER objects
1591 ****************************/
1594 * Implements the "BOX" GIFBUILDER object
1596 * @param pointer GDlib image pointer
1597 * @param array TypoScript array with configuration for the GIFBUILDER object.
1598 * @param array The current working area coordinates.
1600 * @see tslib_gifBuilder::make()
1602 function makeBox(&$im,$conf,$workArea) {
1603 $cords = t3lib_div
::intExplode(',',$conf['dimensions'].',,,');
1604 $conf['offset']=$cords[0].','.$cords[1];
1605 $cords = $this->objPosition($conf,$workArea,Array($cords[2],$cords[3]));
1606 $cols=$this->convertColor($conf['color']);
1607 if (!$this->truecolor
) {
1608 $reduce = t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256);
1609 $this->reduceColors($im, $reduce-1, $reduce-2); // If "reduce-1" colors (or more) are used reduce them to "reduce-2"
1613 if (isset($conf['opacity'])) {
1615 // PHP 0 = opaque, 127 = transparent
1616 // TYPO3 100 = opaque, 0 = transparent
1617 $opacity = t3lib_div
::intInRange(intval($conf['opacity']), 1, 100, 1);
1618 $opacity = abs($opacity - 100);
1619 $opacity = round((127 * $opacity) / 100);
1622 $tmpColor = ImageColorAllocateAlpha($im, $cols[0],$cols[1],$cols[2], $opacity);
1623 imagefilledrectangle($im, $cords[0], $cords[1], $cords[0]+
$cords[2]-1, $cords[1]+
$cords[3]-1, $tmpColor);
1627 * Implements the "Ellipse" GIFBUILDER object
1628 * Example Typoscript:
1635 * 10.dimensions = 100,100,50,50
1639 * $conf['dimensions'] = offset x, offset y, width of ellipse, height of ellipse
1641 * @param pointer GDlib image pointer
1642 * @param array $conf TypoScript array with configuration for the GIFBUILDER object.
1643 * @param array $workArea The current working area coordinates.
1645 * @see tslib_gifBuilder::make()
1647 public function makeEllipse(&$im, array $conf, array $workArea) {
1648 $ellipseConfiguration = t3lib_div
::intExplode(',', $conf['dimensions'] . ',,,');
1649 $conf['offset'] = $ellipseConfiguration[0] . ',' . $ellipseConfiguration[1]; // ellipse offset inside workArea (x/y)
1652 $imageCoordinates = $this->objPosition($conf, $workArea, array($ellipseConfiguration[2], $ellipseConfiguration[3]));
1654 $color = $this->convertColor($conf['color']);
1655 $fillingColor = imagecolorallocate($im, $color[0], $color[1], $color[2]);
1656 imagefilledellipse($im, $imageCoordinates[0], $imageCoordinates[1], $imageCoordinates[2], $imageCoordinates[3], $fillingColor);
1660 * Implements the "EFFECT" GIFBUILDER object
1661 * The operation involves ImageMagick for applying effects
1663 * @param pointer GDlib image pointer
1664 * @param array TypoScript array with configuration for the GIFBUILDER object.
1666 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
1668 function makeEffect(&$im, $conf) {
1669 $commands = $this->IMparams($conf['value']);
1671 $this->applyImageMagickToPHPGif($im, $commands);
1676 * Creating ImageMagick paramters from TypoScript property
1678 * @param string A string with effect keywords=value pairs separated by "|"
1679 * @return string ImageMagick prepared parameters.
1683 function IMparams($setup) {
1684 if (!trim($setup)){return '';}
1685 $effects = explode('|', $setup);
1687 foreach ($effects as $val) {
1688 $pairs=explode('=',$val,2);
1689 $value = trim($pairs[1]);
1690 $effect = strtolower(trim($pairs[0]));
1693 $commands.=' -gamma '.doubleval($value);
1696 if (!$this->NO_IM_EFFECTS
) {
1697 if ($this->V5_EFFECTS
) {
1698 $commands.=$this->v5_blur($value);
1700 $commands.=' -blur '.t3lib_div
::intInRange($value,1,99);
1705 if (!$this->NO_IM_EFFECTS
) {
1706 if ($this->V5_EFFECTS
) {
1707 $commands.=$this->v5_sharpen($value);
1709 $commands.=' -sharpen '.t3lib_div
::intInRange($value,1,99);
1714 $commands.=' -rotate '.t3lib_div
::intInRange($value,0,360);
1717 $commands.=' -solarize '.t3lib_div
::intInRange($value,0,99);
1720 $commands.=' -swirl '.t3lib_div
::intInRange($value,0,1000);
1723 $params = t3lib_div
::intExplode(',',$value);
1724 $commands.=' -wave '.t3lib_div
::intInRange($params[0],0,99).'x'.t3lib_div
::intInRange($params[1],0,99);
1727 $commands.=' -charcoal '.t3lib_div
::intInRange($value,0,100);
1730 $commands.=' -colorspace GRAY';
1733 $commands.=' -edge '.t3lib_div
::intInRange($value,0,99);
1736 $commands.=' -emboss';
1739 $commands.=' -flip';
1742 $commands.=' -flop';
1745 $commands.=' -colors '.t3lib_div
::intInRange($value,2,255);
1748 $commands.=' -shear '.t3lib_div
::intInRange($value,-90,90);
1751 $commands.=' -negate';
1759 * Implements the "ADJUST" GIFBUILDER object
1761 * @param pointer GDlib image pointer
1762 * @param array TypoScript array with configuration for the GIFBUILDER object.
1764 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1766 function adjust(&$im, $conf) {
1767 $setup = $conf['value'];
1768 if (!trim($setup)){return '';}
1769 $effects = explode('|', $setup);
1770 foreach ($effects as $val) {
1771 $pairs=explode('=',$val,2);
1772 $value = trim($pairs[1]);
1773 $effect = strtolower(trim($pairs[0]));
1775 case 'inputlevels': // low,high
1776 $params = t3lib_div
::intExplode(',',$value);
1777 $this->inputLevels($im,$params[0],$params[1]);
1779 case 'outputlevels':
1780 $params = t3lib_div
::intExplode(',',$value);
1781 $this->outputLevels($im,$params[0],$params[1]);
1784 $this->autoLevels($im);
1791 * Implements the "CROP" GIFBUILDER object
1793 * @param pointer GDlib image pointer
1794 * @param array TypoScript array with configuration for the GIFBUILDER object.
1796 * @see tslib_gifBuilder::make()
1798 function crop(&$im,$conf) {
1799 $this->setWorkArea(''); // clears workArea to total image
1800 $cords = t3lib_div
::intExplode(',',$conf['crop'].',,,');
1801 $conf['offset']=$cords[0].','.$cords[1];
1802 $cords = $this->objPosition($conf,$this->workArea
,Array($cords[2],$cords[3]));
1804 $newIm = imagecreatetruecolor($cords[2], $cords[3]);
1805 $cols=$this->convertColor($conf['backColor']?
$conf['backColor']:$this->setup
['backColor']);
1806 $Bcolor = ImageColorAllocate($newIm, $cols[0],$cols[1],$cols[2]);
1807 ImageFilledRectangle($newIm, 0, 0, $cords[2], $cords[3], $Bcolor);
1810 $workArea = Array(0,0,$cords[2],$cords[3]);
1811 if ($cords[0]<0) {$workArea[0]=abs($cords[0]);} else {$newConf['offset']=-$cords[0];}
1812 if ($cords[1]<0) {$workArea[1]=abs($cords[1]);} else {$newConf['offset'].=','.-$cords[1];}
1814 $this->copyGifOntoGif($newIm,$im,$newConf,$workArea);
1816 $this->w
= imagesx($im);
1817 $this->h
= imagesy($im);
1818 $this->setWorkArea(''); // clears workArea to total image
1822 * Implements the "SCALE" GIFBUILDER object
1824 * @param pointer GDlib image pointer
1825 * @param array TypoScript array with configuration for the GIFBUILDER object.
1827 * @see tslib_gifBuilder::make()
1829 function scale(&$im,$conf) {
1830 if ($conf['width'] ||
$conf['height'] ||
$conf['params']) {
1831 $tmpStr = $this->randomName();
1832 $theFile = $tmpStr.'.'.$this->gifExtension
;
1833 $this->ImageWrite($im, $theFile);
1834 $theNewFile = $this->imageMagickConvert($theFile,$this->gifExtension
,$conf['width'],$conf['height'],$conf['params'],'','');
1835 $tmpImg = $this->imageCreateFromFile($theNewFile[3]);
1839 $this->w
= imagesx($im);
1840 $this->h
= imagesy($im);
1841 $this->setWorkArea(''); // clears workArea to total image
1843 if (!$this->dontUnlinkTempFiles
) {
1845 if ($theNewFile[3] && $theNewFile[3]!=$theFile) {
1846 unlink($theNewFile[3]);
1853 * Implements the "WORKAREA" GIFBUILDER object when setting it
1854 * Setting internal working area boundaries (->workArea)
1856 * @param string Working area dimensions, comma separated
1859 * @see tslib_gifBuilder::make()
1861 function setWorkArea($workArea) {
1862 $this->workArea
= t3lib_div
::intExplode(',',$workArea);
1863 $this->workArea
= $this->applyOffset($this->workArea
,$this->OFFSET
);
1864 if (!$this->workArea
[2]) {$this->workArea
[2]=$this->w
;}
1865 if (!$this->workArea
[3]) {$this->workArea
[3]=$this->h
;}
1890 /*************************
1892 * Adjustment functions
1894 ************************/
1897 * Apply auto-levels to input image pointer
1899 * @param integer GDlib Image Pointer
1902 function autolevels(&$im) {
1903 $totalCols = ImageColorsTotal($im);
1906 for ($c=0; $c<$totalCols; $c++
) {
1907 $cols = ImageColorsForIndex($im,$c);
1908 $grayArr[] = round(($cols['red']+
$cols['green']+
$cols['blue'])/3);
1914 for ($c=0; $c<$totalCols; $c++
) {
1915 $cols = ImageColorsForIndex($im,$c);
1916 $cols['red'] = floor(($cols['red']-$min)/$delta*255);
1917 $cols['green'] = floor(($cols['green']-$min)/$delta*255);
1918 $cols['blue'] = floor(($cols['blue']-$min)/$delta*255);
1919 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1925 * Apply output levels to input image pointer (decreasing contrast)
1927 * @param integer GDlib Image Pointer
1928 * @param integer The "low" value (close to 0)
1929 * @param integer The "high" value (close to 255)
1930 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1933 function outputLevels(&$im,$low,$high,$swap='') {
1935 $low = t3lib_div
::intInRange($low,0,255);
1936 $high = t3lib_div
::intInRange($high,0,255);
1944 $delta = $high-$low;
1945 $totalCols = ImageColorsTotal($im);
1946 for ($c=0; $c<$totalCols; $c++
) {
1947 $cols = ImageColorsForIndex($im,$c);
1948 $cols['red'] = $low+
floor($cols['red']/255*$delta);
1949 $cols['green'] = $low+
floor($cols['green']/255*$delta);
1950 $cols['blue'] = $low+
floor($cols['blue']/255*$delta);
1951 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1957 * Apply input levels to input image pointer (increasing contrast)
1959 * @param integer GDlib Image Pointer
1960 * @param integer The "low" value (close to 0)
1961 * @param integer The "high" value (close to 255)
1962 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1965 function inputLevels(&$im,$low,$high,$swap='') {
1967 $low = t3lib_div
::intInRange($low,0,255);
1968 $high = t3lib_div
::intInRange($high,0,255);
1976 $delta = $high-$low;
1977 $totalCols = ImageColorsTotal($im);
1978 for ($c=0; $c<$totalCols; $c++
) {
1979 $cols = ImageColorsForIndex($im,$c);
1980 $cols['red'] = t3lib_div
::intInRange(($cols['red']-$low)/$delta*255, 0,255);
1981 $cols['green'] = t3lib_div
::intInRange(($cols['green']-$low)/$delta*255, 0,255);
1982 $cols['blue'] = t3lib_div
::intInRange(($cols['blue']-$low)/$delta*255, 0,255);
1983 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1989 * Reduce colors in image dependend on the actual amount of colors (Only works if we are not in truecolor mode)
1990 * This function is not needed anymore, as truecolor is now always on.
1992 * @param integer GDlib Image Pointer
1993 * @param integer The max number of colors in the image before a reduction will happen; basically this means that IF the GD image current has the same amount or more colors than $limit define, THEN a reduction is performed.
1994 * @param integer Number of colors to reduce the image to.
1996 * @deprecated since TYPO3 4.4, this function will be removed in TYPO3 4.6.
1998 function reduceColors(&$im,$limit, $cols) {
1999 t3lib_div
::logDeprecatedFunction();
2001 if (!$this->truecolor
&& ImageColorsTotal($im)>=$limit) {
2002 $this->makeEffect($im, Array('value'=>'colors='.$cols) );
2007 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
2009 * @param string Image file to reduce
2010 * @param integer Number of colors to reduce the image to.
2011 * @return string Reduced file
2013 function IMreduceColors($file, $cols) {
2014 $fI = t3lib_div
::split_fileref($file);
2015 $ext = strtolower($fI['fileext']);
2016 $result = $this->randomName().'.'.$ext;
2017 if (($reduce = t3lib_div
::intInRange($cols, 0, ($ext=='gif'?
256:$this->truecolorColors
), 0))>0) {
2018 $params = ' -colors '.$reduce;
2019 if (!$this->im_version_4
) {
2020 // IM4 doesn't have this options but forces them automatically if applicaple (<256 colors in image)
2021 if ($reduce<=256) { $params .= ' -type Palette'; }
2022 if ($ext=='png' && $reduce<=256) { $prefix = 'png8:'; }
2024 $this->imageMagickExec($file, $prefix.$result, $params);
2042 /*********************************
2044 * GIFBUILDER Helper functions
2046 *********************************/
2049 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
2050 * Use PATH_site unless we are in the backend.
2051 * Call it by t3lib_stdGraphic::prependAbsolutePath()
2053 * @param string The font file
2054 * @return string The font file with absolute path.
2056 function prependAbsolutePath($fontFile) {
2057 $absPath = defined('PATH_typo3') ?
dirname(PATH_thisScript
).'/' :PATH_site
;
2058 $fontFile = t3lib_div
::isAbsPath($fontFile) ?
$fontFile : t3lib_div
::resolveBackPath($absPath.$fontFile);
2063 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
2064 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
2066 * @param integer The sharpening factor, 0-100 (effectively in 10 steps)
2067 * @return string The sharpening command, eg. " -sharpen 3x4"
2068 * @see makeText(), IMparams(), v5_blur()
2070 function v5_sharpen($factor) {
2071 $factor = t3lib_div
::intInRange(ceil($factor/10),0,10);
2073 $sharpenArr=explode(',',','.$this->im5fx_sharpenSteps
);
2074 $sharpenF= trim($sharpenArr[$factor]);
2076 $cmd = ' -sharpen '.$sharpenF;
2082 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
2083 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
2085 * @param integer The blurring factor, 0-100 (effectively in 10 steps)
2086 * @return string The blurring command, eg. " -blur 3x4"
2087 * @see makeText(), IMparams(), v5_sharpen()
2089 function v5_blur($factor) {
2090 $factor = t3lib_div
::intInRange(ceil($factor/10),0,10);
2092 $blurArr=explode(',',','.$this->im5fx_blurSteps
);
2093 $blurF= trim($blurArr[$factor]);
2095 $cmd=' -blur '.$blurF;
2101 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
2102 * 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.
2106 function randomName() {
2107 $this->createTempSubDir('temp/');
2108 return $this->tempPath
.'temp/'.md5(uniqid(''));
2112 * Applies offset value to coordinated in $cords.
2113 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
2115 * @param array Integer coordinates in key 0/1
2116 * @param array Offset values in key 0/1
2117 * @return array Modified $cords array
2119 function applyOffset($cords,$OFFSET) {
2120 $cords[0] = intval($cords[0])+
intval($OFFSET[0]);
2121 $cords[1] = intval($cords[1])+
intval($OFFSET[1]);
2126 * Converts a "HTML-color" TypoScript datatype to RGB-values.
2129 * @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
2130 * @return array RGB values in key 0/1/2 of the array
2132 function convertColor($string) {
2134 $cParts = explode(':',$string,2);
2136 // Finding the RGB definitions of the color:
2138 if (strstr($string,'#')) {
2139 $string = preg_replace('/[^A-Fa-f0-9]*/','',$string);
2140 $col[]=HexDec(substr($string,0,2));
2141 $col[]=HexDec(substr($string,2,2));
2142 $col[]=HexDec(substr($string,4,2));
2143 } elseif (strstr($string,',')) {
2144 $string = preg_replace('/[^,0-9]*/','',$string);
2145 $strArr = explode(',',$string);
2146 $col[]=intval($strArr[0]);
2147 $col[]=intval($strArr[1]);
2148 $col[]=intval($strArr[2]);
2150 $string = strtolower(trim($string));
2151 if ($this->colMap
[$string]) {
2152 $col = $this->colMap
[$string];
2154 $col = Array(0,0,0);
2157 // ... and possibly recalculating the value
2158 if (trim($cParts[1])) {
2159 $cParts[1]=trim($cParts[1]);
2160 if (substr($cParts[1],0,1)=='*') {
2161 $val=doubleval(substr($cParts[1],1));
2162 $col[0]=t3lib_div
::intInRange($col[0]*$val,0,255);
2163 $col[1]=t3lib_div
::intInRange($col[1]*$val,0,255);
2164 $col[2]=t3lib_div
::intInRange($col[2]*$val,0,255);
2166 $val=intval($cParts[1]);
2167 $col[0]=t3lib_div
::intInRange($col[0]+
$val,0,255);
2168 $col[1]=t3lib_div
::intInRange($col[1]+
$val,0,255);
2169 $col[2]=t3lib_div
::intInRange($col[2]+
$val,0,255);
2177 * Used with text strings for fonts when languages has other character sets.
2179 * @param string The text to recode
2180 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. { or &#quot; which should render as real chars).
2182 function recodeString($string) {
2183 // Recode string to UTF-8 from $this->nativeCharset:
2184 if ($this->nativeCharset
&& $this->nativeCharset
!='utf-8') {
2185 $string = $this->csConvObj
->utf8_encode($string,$this->nativeCharset
); // Convert to UTF-8
2188 // Recode string accoding to TTFLocaleConv. Deprecated.
2189 if ($this->TTFLocaleConv
) {
2190 t3lib_div
::deprecationLog('The option $TYPO3_CONF_VARS[\'GFX\'][\'TTFLocaleConv\'] is in use, but deprecated since TYPO3 3.6, will be removed in TYPO3 4.6. Make sure to unset this variable in your typo3conf/localconf.php and use a different way to encode your string.');
2192 list($from, $to) = t3lib_div
::trimExplode('..', $this->TTFLocaleConv
, true);
2193 $string = $this->csConvObj
->conv($string, $from, $to);
2200 * Split a string into an array of individual characters
2201 * 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.
2203 * @param string The text string to split
2204 * @param boolean Return Unicode numbers instead of chars.
2205 * @return array Numerical array with a char as each value.
2207 function singleChars($theText,$returnUnicodeNumber=FALSE) {
2208 if ($this->nativeCharset
) {
2209 return $this->csConvObj
->utf8_to_numberarray($theText,1,$returnUnicodeNumber ?
0 : 1); // Get an array of separated UTF-8 chars
2212 $c=strlen($theText);
2213 for($a=0;$a<$c;$a++
) {
2214 $output[]=substr($theText,$a,1);
2221 * 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
2223 * @param array TypoScript configuration for a GIFBUILDER object
2224 * @param array Workarea definition
2225 * @param array BB (Bounding box) array. Not just used for TEXT objects but also for others
2226 * @return array [0]=x, [1]=y, [2]=w, [3]=h
2228 * @see copyGifOntoGif(), makeBox(), crop()
2230 function objPosition($conf,$workArea,$BB) {
2231 // offset, align, valign, workarea
2233 $result[2] = $BB[0];
2234 $result[3] = $BB[1];
2238 $align = explode(',',$conf['align']);
2239 $align[0] = strtolower(substr(trim($align[0]),0,1));
2240 $align[1] = strtolower(substr(trim($align[1]),0,1));
2244 $result[0]=$w-$result[2];
2247 $result[0] = round(($w-$result[2])/2);
2255 $result[1] = $h-$result[3]; // y pos
2258 $result[1] = round(($h-$result[3])/2);
2264 $result = $this->applyOffset($result,t3lib_div
::intExplode(',',$conf['offset']));
2265 $result = $this->applyOffset($result,$workArea);
2289 /***********************************
2291 * Scaling, Dimensions of images
2293 ***********************************/
2296 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
2298 * @param string The image filepath
2299 * @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.
2300 * @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
2301 * @param string Height. See $w
2302 * @param string Additional ImageMagick parameters.
2303 * @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...
2304 * @param array An array with options passed to getImageScale (see this function).
2305 * @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.
2306 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
2307 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
2309 function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0) {
2310 if ($this->NO_IMAGE_MAGICK
) {
2311 // Returning file info right away
2312 return $this->getImageDimensions($imagefile);
2315 if($info=$this->getImageDimensions($imagefile)) {
2316 $newExt=strtolower(trim($newExt));
2317 if (!$newExt) { // If no extension is given the original extension is used
2320 if ($newExt=='web') {
2321 if (t3lib_div
::inList($this->webImageExt
,$info[2])) {
2324 $newExt = $this->gif_or_jpg($info[2],$info[0],$info[1]);
2326 $params = $this->cmds
[$newExt];
2330 if (t3lib_div
::inList($this->imageFileExt
,$newExt)) {
2331 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
2333 $data = $this->getImageScale($info,$w,$h,$options);
2337 // if no conversion should be performed
2338 // this flag is true if the width / height does NOT dictate
2339 // the image to be scaled!! (that is if no width / height is
2340 // given or if the destination w/h matches the original image
2341 // dimensions or if the option to not scale the image is set)
2342 $noScale = (!$w && !$h) ||
($data[0] == $info[0] && $data[1] == $info[1]) ||
$options['noScale'];
2344 if ($noScale && !$data['crs'] && !$params && !$frame && $newExt == $info[2] && !$mustCreate) {
2345 // set the new width and height before returning,
2346 // if the noScale option is set
2347 if ($options['noScale']) {
2348 $info[0] = $data[0];
2349 $info[1] = $data[1];
2351 $info[3] = $imagefile;
2357 $frame = $this->noFramePrepended ?
'' : intval($frame);
2360 $params = $this->cmds
[$newExt];
2365 if (!$data['origW']) { $data['origW'] = $data[0]; }
2366 if (!$data['origH']) { $data['origH'] = $data[1]; }
2367 $offsetX = intval(($data[0] - $data['origW']) * ($data['cropH']+
100)/200);
2368 $offsetY = intval(($data[1] - $data['origH']) * ($data['cropV']+
100)/200);
2369 $params .= ' -crop '.$data['origW'].'x'.$data['origH'].'+'.$offsetX.'+'.$offsetY.' ';
2372 $command = $this->scalecmd
.' '.$info[0].'x'.$info[1].'! '.$params.' ';
2373 $cropscale = ($data['crs'] ?
'crs-V'.$data['cropV'].'H'.$data['cropH'] : '');
2375 if ($this->alternativeOutputKey
) {
2376 $theOutputName = t3lib_div
::shortMD5($command.$cropscale.basename($imagefile).$this->alternativeOutputKey
.'['.$frame.']');
2378 $theOutputName = t3lib_div
::shortMD5($command.$cropscale.$imagefile.filemtime($imagefile).'['.$frame.']');
2380 if ($this->imageMagickConvert_forceFileNameBody
) {
2381 $theOutputName = $this->imageMagickConvert_forceFileNameBody
;
2382 $this->imageMagickConvert_forceFileNameBody
='';
2385 // Making the temporary filename:
2386 $this->createTempSubDir('pics/');
2387 $output = $this->absPrefix
.$this->tempPath
.'pics/'.$this->filenamePrefix
.$theOutputName.'.'.$newExt;
2389 // Register temporary filename:
2390 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
2392 if ($this->dontCheckForExistingTempFile ||
!$this->file_exists_typo3temp_file($output, $imagefile)) {
2393 $this->imageMagickExec($imagefile, $output, $command, $frame);
2395 if (file_exists($output)) {
2398 if ($params) { // params could realisticly change some imagedata!
2399 $info=$this->getImageDimensions($info[3]);
2401 if ($info[2]==$this->gifExtension
&& !$this->dontCompress
) {
2402 t3lib_div
::gif_compress($info[3],''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2411 * Gets the input image dimensions.
2413 * @param string The image filepath
2414 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2415 * @see imageMagickConvert(), tslib_cObj::getImgResource()
2417 function getImageDimensions($imageFile) {
2418 preg_match('/([^\.]*)$/',$imageFile,$reg);
2419 if (file_exists($imageFile) && t3lib_div
::inList($this->imageFileExt
,strtolower($reg[0]))) {
2420 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
2423 if ($temp = @getImageSize
($imageFile)) {
2424 $returnArr = Array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
2426 $returnArr = $this->imageMagickIdentify($imageFile);
2429 $this->cacheImageDimensions($returnArr);
2438 * Cache the result of the getImageDimensions function into the database. Does not check if the
2441 * @param array $identifyResult: Result of the getImageDimensions function
2442 * @return boolean True if operation was successful
2443 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2445 function cacheImageDimensions($identifyResult) {
2447 // Create a md5 hash of the filename
2448 $md5Hash = md5_file($identifyResult[3]);
2451 'md5hash' => $md5Hash,
2452 'md5filename' => md5($identifyResult[3]),
2453 'tstamp' => $GLOBALS['EXEC_TIME'],
2454 'filename' => $identifyResult[3],
2455 'imagewidth' => $identifyResult[0],
2456 'imageheight' => $identifyResult[1],
2458 $TYPO3_DB->exec_INSERTquery('cache_imagesizes', $fieldArr);
2459 if (!$err = $TYPO3_DB->sql_error()) {
2467 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
2469 * @param string The image filepath
2470 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2471 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2473 function getCachedImageDimensions($imageFile) {
2475 // Create a md5 hash of the filename
2476 $md5Hash = md5_file($imageFile);
2477 preg_match('/([^\.]*)$/',$imageFile,$reg);
2478 $res = $TYPO3_DB->exec_SELECTquery ('md5hash, imagewidth, imageheight', 'cache_imagesizes', 'md5filename='.$TYPO3_DB->fullQuoteStr(md5($imageFile),'cache_imagesizes'));
2480 if ($row = $TYPO3_DB->sql_fetch_assoc($res)) {
2481 if ($row['md5hash']!=$md5Hash) {
2482 // file has changed, delete the row
2483 $TYPO3_DB->exec_DELETEquery ('cache_imagesizes', 'md5hash='.$TYPO3_DB->fullQuoteStr($row['md5hash'],'cache_imagesizes'));
2485 return (array((int) $row['imagewidth'], (int) $row['imageheight'], strtolower($reg[0]), $imageFile));
2493 * Get numbers for scaling the image based on input
2495 * @param array Current image information: Width, Height etc.
2496 * @param integer "required" width
2497 * @param integer "required" height
2498 * @param array Options: Keys are like "maxW", "maxH", "minW", "minH"
2501 * @see imageMagickConvert()
2503 function getImageScale($info,$w,$h,$options) {
2504 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
2506 if (strstr($w.$h, 'c')) {
2507 $out['cropH'] = intval(substr(strstr($w, 'c'), 1));
2508 $out['cropV'] = intval(substr(strstr($h, 'c'), 1));
2517 // if there are max-values...
2518 if ($options['maxW']) {
2519 if ($w) { // if width is given...
2520 if ($w>$options['maxW']) {
2521 $w=$options['maxW'];
2522 $max=1; // height should follow
2525 if ($info[0]>$options['maxW']) {
2526 $w=$options['maxW'];
2527 $max=1; // height should follow
2531 if ($options['maxH']) {
2532 if ($h) { // if height is given...
2533 if ($h>$options['maxH']) {
2534 $h=$options['maxH'];
2535 $max=1; // height should follow
2538 if ($info[1]>$options['maxH']) { // Changed [0] to [1] 290801
2539 $h=$options['maxH'];
2540 $max=1; // height should follow
2548 if (!$this->mayScaleUp
) {
2549 if ($w>$info[0]){$w=$info[0];}
2550 if ($h>$info[1]){$h=$info[1];}
2552 if ($w ||
$h) { // if scaling should be performed
2554 $info[1] = ceil($info[1]*($w/$info[0]));
2558 $info[0] = ceil($info[0]*($h/$info[1]));
2563 $ratio = $info[0]/$info[1];
2564 if ($h*$ratio > $w) {
2565 $h = round($w/$ratio);
2567 $w = round($h*$ratio);
2571 $ratio = $info[0] / $info[1];
2572 if ($h * $ratio < $w) {
2573 $h = round($w / $ratio);
2575 $w = round($h * $ratio);
2584 // Set minimum-measures!
2585 if ($options['minW'] && $out[0]<$options['minW']) {
2586 if (($max ||
$crs) && $out[0]) {
2587 $out[1]= round($out[1]*$options['minW']/$out[0]);
2589 $out[0]=$options['minW'];
2591 if ($options['minH'] && $out[1]<$options['minH']) {
2592 if (($max ||
$crs) && $out[1]) {
2593 $out[0]= round($out[0]*$options['minH']/$out[1]);
2595 $out[1]=$options['minH'];
2602 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2604 * @param string Output imagefile
2605 * @param string Original basis file
2606 * @return boolean Returns true if the file is already being made; thus "true" means "Don't render the image again"
2609 function file_exists_typo3temp_file($output,$orig='') {
2610 if ($this->enable_typo3temp_db_tracking
) {
2611 if (file_exists($output)) { // If file exists, then we return immediately
2613 } else { // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2614 $md5Hash=md5($output);
2615 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2617 'cache_typo3temp_log',
2618 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log') . ' AND tstamp>' . ($GLOBALS['EXEC_TIME'] - 30)
2620 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // If there was a record, the image is being generated by another proces (we assume)
2621 if (is_object($GLOBALS['TSFE'])) $GLOBALS['TSFE']->set_no_cache(); // ...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...)
2622 if (is_object($GLOBALS['TT'])) $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: '.$output);
2623 return 2; // Return 'success - 2'
2624 } 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.
2626 $insertFields = array(
2627 'md5hash' => $md5Hash,
2628 'tstamp' => $GLOBALS['EXEC_TIME'],
2629 'filename' => $output,
2630 'orig_filename' => $orig
2632 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
2633 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2635 if (is_object($GLOBALS['TT'])) $GLOBALS['TT']->setTSlogMessage('typo3temp_log: The row did not exist, so a new is written and file is being processed: '.$output);
2640 return file_exists($output);
2661 /***********************************
2663 * ImageMagick API functions
2665 ***********************************/
2668 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2671 * @param string The relative (to PATH_site) image filepath
2674 function imageMagickIdentify($imagefile) {
2675 if (!$this->NO_IMAGE_MAGICK
) {
2676 $frame = $this->noFramePrepended?
'':'[0]';
2677 $cmd = t3lib_div
::imageMagickCommand('identify', $this->wrapFileName($imagefile).$frame);
2678 $returnVal = array();
2679 exec($cmd, $returnVal);
2680 $splitstring=$returnVal[0];
2681 $this->IM_commands
[] = Array ('identify',$cmd,$returnVal[0]);
2683 preg_match('/([^\.]*)$/',$imagefile,$reg);
2684 $splitinfo = explode(' ', $splitstring);
2685 foreach ($splitinfo as $key => $val) {
2687 if ($val) {$temp = explode('x', $val);}
2688 if (intval($temp[0]) && intval($temp[1])) {
2693 if ($dim[0] && $dim[1]) {
2694 return Array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2701 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2702 * Can be used for many things, mostly scaling and effects.
2704 * @param string The relative (to PATH_site) image filepath, input file (read from)
2705 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2706 * @param string ImageMagick parameters
2707 * @param integer Optional, refers to which frame-number to select in the image. '' or 0
2708 * will select the first frame, 1 will select the next and so on...
2709 * @return string The result of a call to PHP function "exec()"
2711 function imageMagickExec($input, $output, $params, $frame = 0) {
2712 if (!$this->NO_IMAGE_MAGICK
) {
2714 // Unless noFramePrepended is set in the Install Tool, a frame number is added to
2715 // select a specific page of the image (by default this will be the first page)
2716 if (!$this->noFramePrepended
) {
2717 $frame = '[' . intval($frame) . ']';
2722 $cmd = t3lib_div
::imageMagickCommand('convert', $params . ' ' . $this->wrapFileName($input) . $frame . ' ' . $this->wrapFileName($output));
2723 $this->IM_commands
[] = array($output,$cmd);
2726 t3lib_div
::fixPermissions($output); // Change the permissions of the file
2733 * 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)
2734 * Can be used for many things, mostly scaling and effects.
2736 * @param string The relative (to PATH_site) image filepath, bottom file
2737 * @param string The relative (to PATH_site) image filepath, overlay file (top)
2738 * @param string The relative (to PATH_site) image filepath, the mask file (grayscale)
2739 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2740 * @param [type] $handleNegation: ...
2743 function combineExec($input,$overlay,$mask,$output, $handleNegation = false) {
2744 if (!$this->NO_IMAGE_MAGICK
) {
2745 $params = '-colorspace GRAY +matte';
2746 if ($handleNegation) {
2747 if ($this->maskNegate
) {
2748 $params .= ' '.$this->maskNegate
;
2751 $theMask = $this->randomName().'.'.$this->gifExtension
;
2752 $this->imageMagickExec($mask, $theMask, $params);
2753 $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
2754 $this->IM_commands
[] = Array ($output,$cmd);
2757 t3lib_div
::fixPermissions($output); // Change the permissions of the file
2759 if (is_file($theMask)) {
2768 * Escapes a file name so it can safely be used on the command line.
2770 * @param string $inputName filename to safeguard, must not be empty
2772 * @return string $inputName escaped as needed
2774 protected function wrapFileName($inputName) {
2775 return escapeshellarg($inputName);
2800 /***********************************
2802 * Various IO functions
2804 ***********************************/
2807 * Returns true if the input file existed
2809 * @param string Input file to check
2810 * @return string Returns the filename if the file existed, otherwise empty.
2812 function checkFile($file) {
2813 if (@is_file
($file)) {
2821 * Creates subdirectory in typo3temp/ if not already found.
2823 * @param string Name of sub directory
2824 * @return boolean Result of t3lib_div::mkdir(), true if it went well.
2826 function createTempSubDir($dirName) {
2828 // Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
2829 if (t3lib_div
::isFirstPartOfStr($this->tempPath
,PATH_site
)) {
2830 $tmpPath = $this->tempPath
;
2832 $tmpPath = PATH_site
.$this->tempPath
;
2835 // Making the temporary filename:
2836 if (!@is_dir
($tmpPath.$dirName)) {
2837 return t3lib_div
::mkdir($tmpPath.$dirName);
2842 * 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.
2844 * @param pointer The image pointer (reference)
2845 * @param string The ImageMagick parameters. Like effects, scaling etc.
2848 function applyImageMagickToPHPGif(&$im, $command) {
2849 $tmpStr = $this->randomName();
2850 $theFile = $tmpStr.'.'.$this->gifExtension
;
2851 $this->ImageWrite($im, $theFile);
2852 $this->imageMagickExec($theFile,$theFile,$command);
2853 $tmpImg = $this->imageCreateFromFile($theFile);
2857 $this->w
= imagesx($im);
2858 $this->h
= imagesy($im);
2860 if (!$this->dontUnlinkTempFiles
) {
2866 * 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.
2867 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2869 * @param string The file extension, lowercase.
2870 * @param integer The width of the output image.
2871 * @param integer The height of the output image.
2872 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2874 function gif_or_jpg($type,$w,$h) {
2875 if ($type=='ai' ||
$w*$h < $this->pixelLimitGif
) {
2876 return $this->gifExtension
;
2883 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2884 * Used in GIFBUILDER
2885 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
2887 * @param string The filename to write to.
2888 * @return string Returns input filename
2889 * @see tslib_gifBuilder::gifBuild()
2891 function output($file) {
2894 preg_match('/([^\.]*)$/',$file,$reg);
2895 $ext=strtolower($reg[0]);
2899 if ($this->ImageWrite($this->im
, $file)) {
2900 // ImageMagick operations
2901 if ($this->setup
['reduceColors'] ||
!$this->png_truecolor
) {
2902 $reduced = $this->IMreduceColors($file, t3lib_div
::intInRange($this->setup
['reduceColors'], 256, $this->truecolorColors
, 256));
2904 @copy
($reduced, $file);
2908 t3lib_div
::gif_compress($file, 'IM'); // Compress with IM! (adds extra compression, LZW from ImageMagick) (Workaround for the absence of lzw-compression in GD)