14050_cleaning_t3lib_arraybrowser
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_stdgraphic.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2010 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
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.
13 *
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.
18 *
19 *
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.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Standard graphical functions
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
32 *
33 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 155: class t3lib_stdGraphic
41 * 236: function init()
42 *
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)
48 *
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)
62 *
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)
68 *
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)
77 *
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)
84 *
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)
95 *
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='')
103 *
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)
109 *
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)
125 *
126 * TOTAL FUNCTIONS: 66
127 * (This index is automatically created/updated by the extension "extdeveval")
128 *
129 */
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146 /**
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
149 *
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.
152 *
153 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
154 * @package TYPO3
155 * @subpackage t3lib
156 * @see tslib_gifBuilder
157 */
158 class t3lib_stdGraphic {
159
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 = '';
176 var $cmds = array(
177 'jpg' => '',
178 'jpeg' => '',
179 'gif' => '',
180 'png' => '-colors 64'
181 );
182 var $NO_IMAGE_MAGICK = '';
183 var $V5_EFFECTS = 0;
184 var $im_version_4 = 0;
185 var $mayScaleUp = 1;
186
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...
194
195 // Internal:
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();
198
199 // Constants:
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)
223 );
224
225 /**
226 * Charset conversion object:
227 *
228 * @var t3lib_cs
229 */
230 var $csConvObj;
231 var $nativeCharset=''; // Is set to the native character set of the input strings.
232
233
234
235
236
237 /**
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.
240 *
241 * @return void
242 */
243 function init() {
244 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
245
246 if (function_exists('imagecreatefromjpeg')&&function_exists('imagejpeg')) {
247 $this->gdlibExtensions .= ',jpg,jpeg';
248 }
249 if (function_exists('imagecreatefrompng')&&function_exists('imagepng')) {
250 $this->gdlibExtensions .= ',png';
251 }
252 if (function_exists('imagecreatefromgif')&&function_exists('imagegif')) {
253 $this->gdlibExtensions .= ',gif';
254 }
255 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['png_truecolor']) {
256 $this->png_truecolor = true;
257 }
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.');
263 }
264
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'] = '';
269 }
270
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;
274
275 if ($gfxConf['im_combine_filename']) $this->combineScript=$gfxConf['im_combine_filename'];
276 if ($gfxConf['im_noFramePrepended']) $this->noFramePrepended=1;
277
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);
281
282 if ($gfxConf['gdlib_png']) {
283 $this->gifExtension='png';
284 }
285 if ($gfxConf['TTFLocaleConv']) {
286 $this->TTFLocaleConv = $gfxConf['TTFLocaleConv'];
287 }
288 if ($gfxConf['enable_typo3temp_db_tracking']) {
289 $this->enable_typo3temp_db_tracking = $gfxConf['enable_typo3temp_db_tracking'];
290 }
291
292 $this->imageFileExt = $gfxConf['imagefile_ext'];
293
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';
301 }
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;
307
308 $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -quality '.$this->jpegQuality;
309 }
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;
314
315 if ($gfxConf['im_v5effects']>0) {
316 $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -quality '.intval($gfxConf['jpg_quality']).$this->v5_sharpen(10);
317 }
318 }
319
320 if (!$gfxConf['im']) {
321 $this->NO_IMAGE_MAGICK = 1;
322 }
323 // Secures that images are not scaled up.
324 if ($gfxConf['im_noScaleUp']) {
325 $this->mayScaleUp=0;
326 }
327
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');
334 }
335 $this->nativeCharset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
336 }
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353 /*************************************************
354 *
355 * Layering images / "IMAGE" GIFBUILDER object
356 *
357 *************************************************/
358
359 /**
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.
363 *
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.
367 * @return void
368 * @see tslib_gifBuilder::make()
369 */
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,'','','','','');
376 } else {
377 $BBimage = $this->getImageDimensions($conf['file']);
378 }
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,'','','','','');
383 } else {
384 $BBmask = $this->getImageDimensions($conf['mask']);
385 }
386 if ($BBimage && $BBmask) {
387 $w = imagesx($im);
388 $h = imagesy($im);
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);
411 // mask the images
412 $this->ImageWrite($im, $theDest);
413
414 $this->combineExec($theDest,$theImage,$theMask,$theDest, true); // Let combineExec handle maskNegation
415
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);
419 $im = $backIm;
420 }
421 // unlink files from process
422 if (!$this->dontUnlinkTempFiles) {
423 unlink($theDest);
424 unlink($theImage);
425 unlink($theMask);
426 }
427 }
428 }
429 }
430
431 /**
432 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is false (using only $conf['file'])
433 *
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.
437 * @return void
438 * @see tslib_gifBuilder::make(), maskImageOntoImage()
439 */
440 function copyImageOntoImage(&$im,$conf,$workArea) {
441 if ($conf['file']) {
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];
445 }
446 $cpImg = $this->imageCreateFromFile($conf['file']);
447 $this->copyGifOntoGif($im,$cpImg,$conf,$workArea);
448 imageDestroy($cpImg);
449 }
450 }
451
452 /**
453 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
454 *
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
460 * @access private
461 */
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]));
469
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
473 // X:
474 if ($Xstart < $workArea[0]) {
475 $cpImgCutX = $workArea[0]-$Xstart;
476 $Xstart = $workArea[0];
477 } else {
478 $cpImgCutX = 0;
479 }
480 $w = $cpW-$cpImgCutX;
481 if ($Xstart > $workArea[0]+$workArea[2]-$w) {
482 $w = $workArea[0]+$workArea[2]-$Xstart;
483 }
484 if ($Xstart < $workArea[0]+$workArea[2]) { // if this image is inside of the workArea, then go on
485 // Y:
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];
492 } else {
493 $cpImgCutY = 0;
494 }
495 $h = $cpH-$cpImgCutY;
496 if ($Ystart > $workArea[1]+$workArea[3]-$h) {
497 $h = $workArea[1]+$workArea[3]-$Ystart;
498 }
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);
501 }
502 }
503 } // Y:
504 }
505 }
506 }
507 }
508
509 /**
510 * Alternative function for using the similar PHP function imagecopyresized(). Used for GD2 only.
511 *
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.
516 * The GD2-fix is to
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.
524 *
525 * For parameters, see PHP function "imagecopyresized()"
526 *
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()"
537 * @return void
538 * @access private
539 * @see t3lib_iconWorks::imagecopyresized()
540 */
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!
549 }
550 } else {
551 imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
552 }
553 }
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576 /********************************
577 *
578 * Text / "TEXT" GIFBUILDER object
579 *
580 ********************************/
581
582 /**
583 * Implements the "TEXT" GIFBUILDER object
584 *
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.
588 * @return void
589 * @see tslib_gifBuilder::make()
590 */
591 function makeText(&$im,$conf,$workArea) {
592 // Spacing
593 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf);
594 // Position
595 $txtPos = $this->txtPosition($conf,$workArea,$conf['BBOX']);
596 $theText = $this->recodeString($conf['text']);
597
598 if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
599 $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2],$txtPos, $conf['imgMap.']), $conf['imgMap.']);
600 }
601 if (!$conf['hideButCreateMap']) {
602 // Font Color:
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"
610 }
611 $Fcolor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
612 // antiAliasing is setup:
613 $Fcolor = ($conf['antiAlias']) ? $Fcolor : -$Fcolor;
614
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.']);
618 } else {
619 $this->renderTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf);
620 }
621 }
622 } else { // NICETEXT::
623 // options anti_aliased and iterations is NOT available when doing this!!
624 $w = imagesx($im);
625 $h = imagesy($im);
626 $tmpStr = $this->randomName();
627
628 $fileMenu = $tmpStr.'_menuNT.'.$this->gifExtension;
629 $fileColor = $tmpStr.'_colorNT.'.$this->gifExtension;
630 $fileMask = $tmpStr.'_maskNT.'.$this->gifExtension;
631 // Scalefactor
632 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
633 $newW = ceil($sF*imagesx($im));
634 $newH = ceil($sF*imagesy($im));
635
636 // Make mask
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);
643 } else {
644 $this->renderTTFText($maskImg, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, $conf['fontFile'], $theText, $conf['splitRendering.'], $conf, $sF);
645 }
646 $this->ImageWrite($maskImg, $fileMask);
647 ImageDestroy($maskImg);
648
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...
653 } else {
654 $command = trim($this->scalecmd.' '.$w.'x'.$h.'! -negate');
655 }
656 } else {
657 if ($this->maskNegate) {
658 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after']);
659 } else {
660 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after'].' -negate');
661 }
662 if ($conf['niceText.']['sharpen']) {
663 if ($this->V5_EFFECTS) {
664 $command.=$this->v5_sharpen($conf['niceText.']['sharpen']);
665 } else {
666 $command.=' -sharpen '.t3lib_div::intInRange($conf['niceText.']['sharpen'],1,99);
667 }
668 }
669 }
670
671 $this->imageMagickExec($fileMask,$fileMask,$command);
672
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);
679
680 // The mask is applied
681 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
682
683 $this->combineExec($fileMenu,$fileColor,$fileMask, $fileMenu);
684
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);
688 $im = $backIm;
689 }
690
691 // Deleting temporary files;
692 if (!$this->dontUnlinkTempFiles) {
693 unlink($fileMenu);
694 unlink($fileColor);
695 unlink($fileMask);
696 }
697 }
698 }
699 }
700
701 /**
702 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
703 *
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
708 * @access private
709 * @see makeText()
710 */
711 function txtPosition($conf,$workArea,$BB) {
712 $bbox = $BB[2];
713 $angle=intval($conf['angle'])/180*pi();
714 $conf['angle']=0;
715 $straightBB = $this->calcBBox($conf);
716
717 // offset, align, valign, workarea
718 $result=Array(); // [0]=x, [1]=y, [2]=w, [3]=h
719 $result[2] = $BB[0];
720 $result[3] = $BB[1];
721 $w=$workArea[2];
722 $h=$workArea[3];
723
724 switch($conf['align']) {
725 case 'right':
726 case 'center':
727 $factor=abs(cos($angle));
728 $sign=(cos($angle)<0)?-1:1;
729 $len1 = $sign*$factor*$straightBB[0];
730 $len2= $sign*$BB[0];
731 $result[0] = $w-ceil($len2*$factor+(1-$factor)*$len1);
732
733 $factor=abs(sin($angle));
734 $sign=(sin($angle)<0)?-1:1;
735 $len1= $sign*$factor*$straightBB[0];
736 $len2= $sign*$BB[1];
737 $result[1]=ceil($len2*$factor+(1-$factor)*$len1);
738 break;
739 }
740 switch($conf['align']) {
741 case 'right':
742 break;
743 case 'center':
744 $result[0] = round(($result[0])/2);
745 $result[1] = round(($result[1])/2);
746 break;
747 default:
748 $result[0]=0;
749 $result[1]=0;
750 break;
751 }
752 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
753 $result = $this->applyOffset($result,$workArea);
754 return $result;
755 }
756
757 /**
758 * Calculates bounding box information for the TEXT GIFBUILDER object.
759 *
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
762 * @access private
763 * @see txtPosition(), tslib_gifBuilder::start()
764 */
765 function calcBBox($conf) {
766 $sF = $this->getTextScalFactor($conf);
767 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf, $sF);
768 $theText = $this->recodeString($conf['text']);
769
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);
777 } else {
778 $x = ($charInf[2]-$charInf[0]);
779 $y = ($charInf[1]-$charInf[7]);
780 }
781 // Set original lineHeight (used by line breaks):
782 $theBBoxInfo['lineHeight'] = $y;
783
784 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
785 $x=0;
786 if (!$spacing && $wordSpacing) {
787 $bits = explode(' ',$theText);
788 foreach ($bits as $word) {
789 $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;
793 }
794 } else {
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);
801 }
802 }
803 } elseif (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($conf['text'], $conf) > $conf['breakWidth']) {
804 $maxWidth = 0;
805 $currentWidth = 0;
806 $breakWidth = $conf['breakWidth'];
807 $breakSpace = $this->getBreakSpace($conf, $theBBoxInfo);
808
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;
815 } else {
816 $maxWidth = max($maxWidth, $currentWidth);
817 $y+= $breakSpace;
818 // Restart:
819 $currentWidth = $wordWidth;
820 }
821 }
822 $x = max($maxWidth, $currentWidth) * $sF;
823 }
824
825 if ($sF > 1) {
826 $x = ceil($x / $sF);
827 $y = ceil($y / $sF);
828 if (is_array($theBBoxInfo)) {
829 foreach ($theBBoxInfo as &$value) {
830 $value = ceil($value / $sF);
831 }
832 }
833 }
834 return array($x, $y, $theBBoxInfo);
835 }
836
837 /**
838 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
839 *
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.
842 * @return void
843 * @access private
844 * @see makeText(), calcTextCordsForMap()
845 */
846 function addToMap($cords,$conf) {
847 $JS = $conf['noBlur'] ? '' : ' onfocus="blurLink(this);"';
848
849 $this->map.='<area'.
850 ' shape="poly"'.
851 ' coords="'.implode(',',$cords).'"'.
852 ' href="'.htmlspecialchars($conf['url']).'"'.
853 ($conf['target'] ? ' target="'.htmlspecialchars($conf['target']).'"' : '').
854 $JS.
855 (strlen($conf['titleText']) ? ' title="'.htmlspecialchars($conf['titleText']).'"' : '').
856 ' alt="'.htmlspecialchars($conf['altText']).'" />';
857 }
858
859 /**
860 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
861 *
862 * @param array Coordinates (from BBOX array)
863 * @param array Offset array
864 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
865 * @return array
866 * @access private
867 * @see makeText(), calcTextCordsForMap()
868 */
869 function calcTextCordsForMap($cords,$offset, $conf) {
870 $pars = t3lib_div::intExplode(',',$conf['explode'].',');
871
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];
880
881 return $newCords;
882 }
883
884 /**
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.
887 * See
888 *
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
901 * @return void
902 * @access private
903 */
904 function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing, $splitRenderingConf, $sF=1) {
905
906 $spacing*=$sF;
907 $wordSpacing*=$sF;
908
909 if (!$spacing && $wordSpacing) {
910 $bits = explode(' ',$text);
911 foreach ($bits as $word) {
912 $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;
917 }
918 } else {
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);
926 }
927 }
928 }
929
930 /**
931 * Function that finds the right fontsize that will render the textstring within a certain width
932 *
933 * @param array The TypoScript properties of the TEXT GIFBUILDER object
934 * @return integer The new fontSize
935 * @access private
936 * @author René Fritz <r.fritz@colorcube.de>
937 * @see tslib_gifBuilder::start()
938 */
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);
943 if ($maxWidth) {
944 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
945 return $conf['fontSize'];
946 // ################ no calc for spacing yet !!!!!!
947 } else {
948 do {
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]);
955 } else {
956 $pixelWidth = abs($bounds[4]-$bounds[6]);
957 }
958
959 // Size is fine, exit:
960 if ($pixelWidth <= $maxWidth) {
961 break;
962 } else {
963 $conf['fontSize']--;
964 }
965 } while ($conf['fontSize']>1);
966 }//if spacing
967 }
968 return $conf['fontSize'];
969 }
970
971 /**
972 * Wrapper for ImageTTFBBox
973 *
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.
981 */
982 function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1) {
983
984 // Initialize:
985 $offsetInfo = array();
986 $stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
987
988 // Traverse string parts:
989 foreach($stringParts as $strCfg) {
990 $fontFile = t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']);
991 if (is_readable($fontFile)) {
992
993 // Calculate Bounding Box for part:
994 $calc = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);
995
996 // Calculate offsets:
997 if (!count($offsetInfo)) {
998 $offsetInfo = $calc; // First run, just copy over.
999 } else {
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']);
1004 }
1005
1006 } else {
1007 debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFBBoxWrapper()');
1008 }
1009 }
1010
1011 return $offsetInfo;
1012 }
1013
1014 /**
1015 * Wrapper for ImageTTFText
1016 *
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
1027 * @return void
1028 */
1029 function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1) {
1030
1031 // Initialize:
1032 $stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
1033 $x = ceil($sF*$x);
1034 $y = ceil($sF*$y);
1035
1036 // Traverse string parts:
1037 foreach($stringParts as $i => $strCfg) {
1038
1039 // Initialize:
1040 $colorIndex = $color;
1041
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;
1047 }
1048
1049 // Setting xSpaceBefore
1050 if ($i) {
1051 $x+= intval($strCfg['xSpaceBefore']);
1052 $y-= intval($strCfg['ySpaceBefore']);
1053 }
1054
1055 $fontFile = t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']);
1056 if (is_readable($fontFile)) {
1057
1058 // Render part:
1059 ImageTTFText($im, t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
1060
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']);
1065
1066 } else {
1067 debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFTextWrapper()');
1068 }
1069
1070 }
1071 }
1072
1073 /**
1074 * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
1075 *
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
1081 */
1082 function splitString($string,$splitRendering,$fontSize,$fontFile) {
1083
1084 // Initialize by setting the whole string and default configuration as the first entry.
1085 $result = array();
1086 $result[] = array(
1087 'str' => $string,
1088 'fontSize' => $fontSize,
1089 'fontFile' => $fontFile
1090 );
1091
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);
1096
1097 // Traverse configured options:
1098 foreach($sKeyArray as $key) {
1099 $cfg = $splitRendering[$key.'.'];
1100
1101 // Process each type of split rendering keyword:
1102 switch((string)$splitRendering[$key]) {
1103 case 'highlightWord':
1104 if (strlen($cfg['value'])) {
1105 $newResult = array();
1106
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));
1114 }
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'],
1125 );
1126 }
1127 }
1128 }
1129
1130 // Set the new result as result array:
1131 if (count($newResult)) {
1132 $result = $newResult;
1133 }
1134 }
1135 break;
1136 case 'charRange':
1137 if (strlen($cfg['value'])) {
1138
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];
1144 }
1145 $newResult = array();
1146
1147 // Traverse the current parts of the result array:
1148 foreach($result as $part) {
1149
1150 // Initialize:
1151 $currentState = -1;
1152 $bankAccum = '';
1153
1154 // Explode the string value by the word value to highlight:
1155 $utf8Chars = $this->singleChars($part['str']);
1156 foreach($utf8Chars as $utfChar) {
1157
1158 // Find number and evaluate position:
1159 $uNumber = $this->csConvObj->utf8CharToUnumber($utfChar);
1160 $inRange = 0;
1161 foreach($ranges as $rangeDef) {
1162 if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] || $uNumber <= $rangeDef[1])) {
1163 $inRange = 1;
1164 break;
1165 }
1166 }
1167 if ($currentState==-1) $currentState = $inRange; // Initialize first char
1168
1169 // Switch bank:
1170 if ($inRange != $currentState && !t3lib_div::inList('32,10,13,9',$uNumber)) {
1171
1172 // Set result:
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'] : '',
1183 );
1184 }
1185
1186 // Initialize new settings:
1187 $currentState = $inRange;
1188 $bankAccum = '';
1189 }
1190
1191 // Add char to bank:
1192 $bankAccum.=$utfChar;
1193 }
1194
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'] : '',
1206 );
1207 }
1208 }
1209
1210 // Set the new result as result array:
1211 if (count($newResult)) {
1212 $result = $newResult;
1213 }
1214 }
1215 break;
1216 }
1217 }
1218 }
1219
1220 return $result;
1221 }
1222
1223 /**
1224 * Calculates the spacing and wordSpacing values
1225 *
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)
1229 * @access private
1230 * @see calcBBox()
1231 */
1232 function calcWordSpacing($conf, $scaleFactor=1) {
1233
1234 $spacing = intval($conf['spacing']);
1235 $wordSpacing = intval($conf['wordSpacing']);
1236 $wordSpacing = $wordSpacing?$wordSpacing:$spacing*2;
1237
1238 $spacing*=$scaleFactor;
1239 $wordSpacing*=$scaleFactor;
1240
1241 return array($spacing,$wordSpacing);
1242 }
1243
1244 /**
1245 * Calculates and returns the niceText.scaleFactor
1246 *
1247 * @param array TypoScript array for the TEXT GIFBUILDER object
1248 * @return integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1249 * @access private
1250 */
1251 function getTextScalFactor($conf) {
1252 if (!$conf['niceText']) {
1253 $sF = 1;
1254 } else { // NICETEXT::
1255 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
1256 }
1257 return $sF;
1258 }
1259
1260 /**
1261 * Renders a regular text and takes care of a possible line break automatically.
1262 *
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
1274 * @return void
1275 */
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']) {
1278 $phrase = '';
1279 $currentWidth = 0;
1280
1281 $breakWidth = $conf['breakWidth'];
1282 $breakSpace = $this->getBreakSpace($conf);
1283
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;
1291 } else {
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:
1295 $y+= $breakSpace;
1296 // Restart the phrase:
1297 $currentWidth = $wordWidth;
1298 $phrase = $wordPair;
1299 }
1300 }
1301 // Render the remaining phrase:
1302 if ($currentWidth) {
1303 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1304 }
1305 } else {
1306 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
1307 }
1308 }
1309
1310 /**
1311 * Gets the word pairs used for automatic line breaks.
1312 *
1313 * @param string $string
1314 * @return array
1315 */
1316 protected function getWordPairsForLineBreak($string) {
1317 $wordPairs = array();
1318
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];
1323 }
1324
1325 return $wordPairs;
1326 }
1327
1328 /**
1329 * Gets the rendered text width.
1330 *
1331 * @param string $text
1332 * @param array $conf
1333 * @param integer
1334 */
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]);
1341 } else {
1342 $pixelWidth = abs($bounds[4]-$bounds[6]);
1343 }
1344 return $pixelWidth;
1345 }
1346
1347 /**
1348 * Gets the break space for each new line.
1349 *
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
1353 */
1354 protected function getBreakSpace($conf, array $boundingBox = NULL) {
1355 if (!isset($boundingBox)) {
1356 $boundingBox = $this->calcBBox($conf);
1357 $boundingBox = $boundingBox[2];
1358 }
1359
1360 if (isset($conf['breakSpace']) && $conf['breakSpace']) {
1361 $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
1362 } else {
1363 $breakSpace = $boundingBox['lineHeight'];
1364 }
1365
1366 return $breakSpace;
1367 }
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379 /*********************************************
1380 *
1381 * Other GIFBUILDER objects related to TEXT
1382 *
1383 *********************************************/
1384
1385 /**
1386 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
1387 *
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.
1392 * @return void
1393 * @see tslib_gifBuilder::make(), makeText()
1394 */
1395 function makeOutline(&$im,$conf,$workArea,$txtConf) {
1396 $thickness = intval($conf['thickness']);
1397 if ($thickness) {
1398 $txtConf['fontColor'] = $conf['color'];
1399 $outLineDist = t3lib_div::intInRange($thickness,1,2);
1400 for ($b=1;$b<=$outLineDist;$b++) {
1401 if ($b==1) {
1402 $it = 8;
1403 } else {
1404 $it = 16;
1405 }
1406 $outL = $this->circleOffset($b, $it);
1407 for ($a=0;$a<$it;$a++) {
1408 $this->makeText($im,$txtConf,$this->applyOffset($workArea,$outL[$a]));
1409 }
1410 }
1411 }
1412 }
1413
1414 /**
1415 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
1416 *
1417 * access private
1418 *
1419 * @param integer Distance
1420 * @param integer Iterations.
1421 * @return array
1422 * @see makeOutline()
1423 */
1424 function circleOffset($distance, $iterations) {
1425 $res = Array();
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);
1433 }
1434 }
1435 return $res;
1436 }
1437
1438 /**
1439 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
1440 *
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.
1445 * @return void
1446 * @see tslib_gifBuilder::make(), makeShadow()
1447 */
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']);
1452 $newOffset[0]*=-1;
1453 $newOffset[1]*=-1;
1454 $conf['offset']=implode(',',$newOffset);
1455 $conf['color']=$conf['lowColor'];
1456 $this->makeShadow($im,$conf,$workArea,$txtConf);
1457 }
1458
1459 /**
1460 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
1461 * The operation involves ImageMagick for combining.
1462 *
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.
1467 * @return void
1468 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
1469 */
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);
1473
1474 if (!$blurRate || $this->NO_IM_EFFECTS) { // No effects if ImageMagick ver. 5+
1475 $txtConf['fontColor'] = $conf['color'];
1476 $this->makeText($im,$txtConf,$workArea);
1477 } else {
1478 $w = imagesx($im);
1479 $h = imagesy($im);
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;
1485
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);
1493
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
1503
1504
1505 $command='';
1506 $command.=$this->maskNegate;
1507
1508 if ($this->V5_EFFECTS) {
1509 $command.=$this->v5_blur($blurRate+1);
1510 } else {
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;
1517 }
1518 }
1519
1520 $this->imageMagickExec($fileMask,$fileMask,$command.' +matte');
1521
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
1524
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
1529
1530 // adjust the mask
1531 $intensity = 40;
1532 if ($conf['intensity']) {
1533 $intensity = t3lib_div::intInRange($conf['intensity'],0,100);
1534 }
1535 $intensity = ceil(255-($intensity/100*255));
1536 $this->inputLevels($blurTextImg,0,$intensity,$this->maskNegate);
1537
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
1542 }
1543
1544 $this->ImageWrite($blurTextImg, $fileMask); // Dump the mask again
1545 ImageDestroy($blurTextImg); // Destroy the mask
1546
1547 // The pictures are combined
1548 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
1549
1550 $this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);
1551
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);
1555 $im = $backIm;
1556 }
1557 }
1558 // Deleting temporary files;
1559 if (!$this->dontUnlinkTempFiles) {
1560 unlink($fileMenu);
1561 unlink($fileColor);
1562 unlink($fileMask);
1563 }
1564 }
1565 }
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587 /****************************
1588 *
1589 * Other GIFBUILDER objects
1590 *
1591 ****************************/
1592
1593 /**
1594 * Implements the "BOX" GIFBUILDER object
1595 *
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.
1599 * @return void
1600 * @see tslib_gifBuilder::make()
1601 */
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"
1610 }
1611
1612 $opacity = 0;
1613 if (isset($conf['opacity'])) {
1614 // conversion:
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);
1620 }
1621
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);
1624 }
1625
1626 /**
1627 * Implements the "Ellipse" GIFBUILDER object
1628 * Example Typoscript:
1629 * file = GIFBUILDER
1630 * file {
1631 * XY = 200,200
1632 * format = jpg
1633 * quality = 100
1634 * 10 = ELLIPSE
1635 * 10.dimensions = 100,100,50,50
1636 * 10.color = red
1637 *
1638 * $workArea = X,Y
1639 * $conf['dimensions'] = offset x, offset y, width of ellipse, height of ellipse
1640 *
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.
1644 * @return void
1645 * @see tslib_gifBuilder::make()
1646 */
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)
1650
1651 // @see objPosition
1652 $imageCoordinates = $this->objPosition($conf, $workArea, array($ellipseConfiguration[2], $ellipseConfiguration[3]));
1653
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);
1657 }
1658
1659 /**
1660 * Implements the "EFFECT" GIFBUILDER object
1661 * The operation involves ImageMagick for applying effects
1662 *
1663 * @param pointer GDlib image pointer
1664 * @param array TypoScript array with configuration for the GIFBUILDER object.
1665 * @return void
1666 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
1667 */
1668 function makeEffect(&$im, $conf) {
1669 $commands = $this->IMparams($conf['value']);
1670 if ($commands) {
1671 $this->applyImageMagickToPHPGif($im, $commands);
1672 }
1673 }
1674
1675 /**
1676 * Creating ImageMagick paramters from TypoScript property
1677 *
1678 * @param string A string with effect keywords=value pairs separated by "|"
1679 * @return string ImageMagick prepared parameters.
1680 * @access private
1681 * @see makeEffect()
1682 */
1683 function IMparams($setup) {
1684 if (!trim($setup)){return '';}
1685 $effects = explode('|', $setup);
1686 $commands = '';
1687 foreach ($effects as $val) {
1688 $pairs=explode('=',$val,2);
1689 $value = trim($pairs[1]);
1690 $effect = strtolower(trim($pairs[0]));
1691 switch($effect) {
1692 case 'gamma':
1693 $commands.=' -gamma '.doubleval($value);
1694 break;
1695 case 'blur':
1696 if (!$this->NO_IM_EFFECTS) {
1697 if ($this->V5_EFFECTS) {
1698 $commands.=$this->v5_blur($value);
1699 } else {
1700 $commands.=' -blur '.t3lib_div::intInRange($value,1,99);
1701 }
1702 }
1703 break;
1704 case 'sharpen':
1705 if (!$this->NO_IM_EFFECTS) {
1706 if ($this->V5_EFFECTS) {
1707 $commands.=$this->v5_sharpen($value);
1708 } else {
1709 $commands.=' -sharpen '.t3lib_div::intInRange($value,1,99);
1710 }
1711 }
1712 break;
1713 case 'rotate':
1714 $commands.=' -rotate '.t3lib_div::intInRange($value,0,360);
1715 break;
1716 case 'solarize':
1717 $commands.=' -solarize '.t3lib_div::intInRange($value,0,99);
1718 break;
1719 case 'swirl':
1720 $commands.=' -swirl '.t3lib_div::intInRange($value,0,1000);
1721 break;
1722 case 'wave':
1723 $params = t3lib_div::intExplode(',',$value);
1724 $commands.=' -wave '.t3lib_div::intInRange($params[0],0,99).'x'.t3lib_div::intInRange($params[1],0,99);
1725 break;
1726 case 'charcoal':
1727 $commands.=' -charcoal '.t3lib_div::intInRange($value,0,100);
1728 break;
1729 case 'gray':
1730 $commands.=' -colorspace GRAY';
1731 break;
1732 case 'edge':
1733 $commands.=' -edge '.t3lib_div::intInRange($value,0,99);
1734 break;
1735 case 'emboss':
1736 $commands.=' -emboss';
1737 break;
1738 case 'flip':
1739 $commands.=' -flip';
1740 break;
1741 case 'flop':
1742 $commands.=' -flop';
1743 break;
1744 case 'colors':
1745 $commands.=' -colors '.t3lib_div::intInRange($value,2,255);
1746 break;
1747 case 'shear':
1748 $commands.=' -shear '.t3lib_div::intInRange($value,-90,90);
1749 break;
1750 case 'invert':
1751 $commands.=' -negate';
1752 break;
1753 }
1754 }
1755 return $commands;
1756 }
1757
1758 /**
1759 * Implements the "ADJUST" GIFBUILDER object
1760 *
1761 * @param pointer GDlib image pointer
1762 * @param array TypoScript array with configuration for the GIFBUILDER object.
1763 * @return void
1764 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1765 */
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]));
1774 switch($effect) {
1775 case 'inputlevels': // low,high
1776 $params = t3lib_div::intExplode(',',$value);
1777 $this->inputLevels($im,$params[0],$params[1]);
1778 break;
1779 case 'outputlevels':
1780 $params = t3lib_div::intExplode(',',$value);
1781 $this->outputLevels($im,$params[0],$params[1]);
1782 break;
1783 case 'autolevels':
1784 $this->autoLevels($im);
1785 break;
1786 }
1787 }
1788 }
1789
1790 /**
1791 * Implements the "CROP" GIFBUILDER object
1792 *
1793 * @param pointer GDlib image pointer
1794 * @param array TypoScript array with configuration for the GIFBUILDER object.
1795 * @return void
1796 * @see tslib_gifBuilder::make()
1797 */
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]));
1803
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);
1808
1809 $newConf = Array();
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];}
1813
1814 $this->copyGifOntoGif($newIm,$im,$newConf,$workArea);
1815 $im = $newIm;
1816 $this->w = imagesx($im);
1817 $this->h = imagesy($im);
1818 $this->setWorkArea(''); // clears workArea to total image
1819 }
1820
1821 /**
1822 * Implements the "SCALE" GIFBUILDER object
1823 *
1824 * @param pointer GDlib image pointer
1825 * @param array TypoScript array with configuration for the GIFBUILDER object.
1826 * @return void
1827 * @see tslib_gifBuilder::make()
1828 */
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]);
1836 if ($tmpImg) {
1837 ImageDestroy($im);
1838 $im = $tmpImg;
1839 $this->w = imagesx($im);
1840 $this->h = imagesy($im);
1841 $this->setWorkArea(''); // clears workArea to total image
1842 }
1843 if (!$this->dontUnlinkTempFiles) {
1844 unlink($theFile);
1845 if ($theNewFile[3] && $theNewFile[3]!=$theFile) {
1846 unlink($theNewFile[3]);
1847 }
1848 }
1849 }
1850 }
1851
1852 /**
1853 * Implements the "WORKAREA" GIFBUILDER object when setting it
1854 * Setting internal working area boundaries (->workArea)
1855 *
1856 * @param string Working area dimensions, comma separated
1857 * @return void
1858 * @access private
1859 * @see tslib_gifBuilder::make()
1860 */
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;}
1866 }
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890 /*************************
1891 *
1892 * Adjustment functions
1893 *
1894 ************************/
1895
1896 /**
1897 * Apply auto-levels to input image pointer
1898 *
1899 * @param integer GDlib Image Pointer
1900 * @return void
1901 */
1902 function autolevels(&$im) {
1903 $totalCols = ImageColorsTotal($im);
1904 $min=255;
1905 $max=0;
1906 for ($c=0; $c<$totalCols; $c++) {
1907 $cols = ImageColorsForIndex($im,$c);
1908 $grayArr[] = round(($cols['red']+$cols['green']+$cols['blue'])/3);
1909 }
1910 $min=min($grayArr);
1911 $max=max($grayArr);
1912 $delta = $max-$min;
1913 if ($delta) {
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']);
1920 }
1921 }
1922 }
1923
1924 /**
1925 * Apply output levels to input image pointer (decreasing contrast)
1926 *
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...)
1931 * @return void
1932 */
1933 function outputLevels(&$im,$low,$high,$swap='') {
1934 if ($low<$high){
1935 $low = t3lib_div::intInRange($low,0,255);
1936 $high = t3lib_div::intInRange($high,0,255);
1937
1938 if ($swap) {
1939 $temp = $low;
1940 $low = 255-$high;
1941 $high = 255-$temp;
1942 }
1943
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']);
1952 }
1953 }
1954 }
1955
1956 /**
1957 * Apply input levels to input image pointer (increasing contrast)
1958 *
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...)
1963 * @return void
1964 */
1965 function inputLevels(&$im,$low,$high,$swap='') {
1966 if ($low<$high){
1967 $low = t3lib_div::intInRange($low,0,255);
1968 $high = t3lib_div::intInRange($high,0,255);
1969
1970 if ($swap) {
1971 $temp = $low;
1972 $low = 255-$high;
1973 $high = 255-$temp;
1974 }
1975
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']);
1984 }
1985 }
1986 }
1987
1988 /**
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.
1991 *
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.
1995 * @return void
1996 * @deprecated since TYPO3 4.4, this function will be removed in TYPO3 4.6.
1997 */
1998 function reduceColors(&$im,$limit, $cols) {
1999 t3lib_div::logDeprecatedFunction();
2000
2001 if (!$this->truecolor && ImageColorsTotal($im)>=$limit) {
2002 $this->makeEffect($im, Array('value'=>'colors='.$cols) );
2003 }
2004 }
2005
2006 /**
2007 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
2008 *
2009 * @param string Image file to reduce
2010 * @param integer Number of colors to reduce the image to.
2011 * @return string Reduced file
2012 */
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:'; }
2023 }
2024 $this->imageMagickExec($file, $prefix.$result, $params);
2025 if ($result) {
2026 return $result;
2027 }
2028 }
2029 return '';
2030 }
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042 /*********************************
2043 *
2044 * GIFBUILDER Helper functions
2045 *
2046 *********************************/
2047
2048 /**
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()
2052 *
2053 * @param string The font file
2054 * @return string The font file with absolute path.
2055 */
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);
2059 return $fontFile;
2060 }
2061
2062 /**
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.
2065 *
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()
2069 */
2070 function v5_sharpen($factor) {
2071 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
2072
2073 $sharpenArr=explode(',',','.$this->im5fx_sharpenSteps);
2074 $sharpenF= trim($sharpenArr[$factor]);
2075 if ($sharpenF) {
2076 $cmd = ' -sharpen '.$sharpenF;
2077 return $cmd;
2078 }
2079 }
2080
2081 /**
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.
2084 *
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()
2088 */
2089 function v5_blur($factor) {
2090 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
2091
2092 $blurArr=explode(',',','.$this->im5fx_blurSteps);
2093 $blurF= trim($blurArr[$factor]);
2094 if ($blurF) {
2095 $cmd=' -blur '.$blurF;
2096 return $cmd;
2097 }
2098 }
2099
2100 /**
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.
2103 *
2104 * @return string
2105 */
2106 function randomName() {
2107 $this->createTempSubDir('temp/');
2108 return $this->tempPath.'temp/'.md5(uniqid(''));
2109 }
2110
2111 /**
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
2114 *
2115 * @param array Integer coordinates in key 0/1
2116 * @param array Offset values in key 0/1
2117 * @return array Modified $cords array
2118 */
2119 function applyOffset($cords,$OFFSET) {
2120 $cords[0] = intval($cords[0])+intval($OFFSET[0]);
2121 $cords[1] = intval($cords[1])+intval($OFFSET[1]);
2122 return $cords;
2123 }
2124
2125 /**
2126 * Converts a "HTML-color" TypoScript datatype to RGB-values.
2127 * Default is 0,0,0
2128 *
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
2131 */
2132 function convertColor($string) {
2133 $col=array();
2134 $cParts = explode(':',$string,2);
2135
2136 // Finding the RGB definitions of the color:
2137 $string=$cParts[0];
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]);
2149 } else {
2150 $string = strtolower(trim($string));
2151 if ($this->colMap[$string]) {
2152 $col = $this->colMap[$string];
2153 } else {
2154 $col = Array(0,0,0);
2155 }
2156 }
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);
2165 } else {
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);
2170 }
2171 }
2172 return $col;
2173 }
2174
2175 /**
2176 * Recode string
2177 * Used with text strings for fonts when languages has other character sets.
2178 *
2179 * @param string The text to recode
2180 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
2181 */
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
2186 }
2187
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.');
2191
2192 list($from, $to) = t3lib_div::trimExplode('..', $this->TTFLocaleConv, true);
2193 $string = $this->csConvObj->conv($string, $from, $to);
2194 }
2195
2196 return $string;
2197 }
2198
2199 /**
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.
2202 *
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.
2206 */
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
2210 } else {
2211 $output=array();
2212 $c=strlen($theText);
2213 for($a=0;$a<$c;$a++) {
2214 $output[]=substr($theText,$a,1);
2215 }
2216 return $output;
2217 }
2218 }
2219
2220 /**
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
2222 *
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
2227 * @access private
2228 * @see copyGifOntoGif(), makeBox(), crop()
2229 */
2230 function objPosition($conf,$workArea,$BB) {
2231 // offset, align, valign, workarea
2232 $result=Array();
2233 $result[2] = $BB[0];
2234 $result[3] = $BB[1];
2235 $w=$workArea[2];
2236 $h=$workArea[3];
2237
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));
2241
2242 switch($align[0]) {
2243 case 'r':
2244 $result[0]=$w-$result[2];
2245 break;
2246 case 'c':
2247 $result[0] = round(($w-$result[2])/2);
2248 break;
2249 default:
2250 $result[0] = 0;
2251 break;
2252 }
2253 switch($align[1]) {
2254 case 'b':
2255 $result[1] = $h-$result[3]; // y pos
2256 break;
2257 case 'c':
2258 $result[1] = round(($h-$result[3])/2);
2259 break;
2260 default:
2261 $result[1]=0;
2262 break;
2263 }
2264 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
2265 $result = $this->applyOffset($result,$workArea);
2266 return $result;
2267 }
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289 /***********************************
2290 *
2291 * Scaling, Dimensions of images
2292 *
2293 ***********************************/
2294
2295 /**
2296 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
2297 *
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()
2308 */
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);
2313 }
2314
2315 if($info=$this->getImageDimensions($imagefile)) {
2316 $newExt=strtolower(trim($newExt));
2317 if (!$newExt) { // If no extension is given the original extension is used
2318 $newExt = $info[2];
2319 }
2320 if ($newExt=='web') {
2321 if (t3lib_div::inList($this->webImageExt,$info[2])) {
2322 $newExt = $info[2];
2323 } else {
2324 $newExt = $this->gif_or_jpg($info[2],$info[0],$info[1]);
2325 if (!$params) {
2326 $params = $this->cmds[$newExt];
2327 }
2328 }
2329 }
2330 if (t3lib_div::inList($this->imageFileExt,$newExt)) {
2331 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
2332
2333 $data = $this->getImageScale($info,$w,$h,$options);
2334 $w=$data['origW'];
2335 $h=$data['origH'];
2336
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'];
2343
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];
2350 }
2351 $info[3] = $imagefile;
2352 return $info;
2353 }
2354 $info[0]=$data[0];
2355 $info[1]=$data[1];
2356
2357 $frame = $this->noFramePrepended ? '' : intval($frame);
2358
2359 if (!$params) {
2360 $params = $this->cmds[$newExt];
2361 }
2362
2363 // Cropscaling:
2364 if ($data['crs']) {
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.' ';
2370 }
2371
2372 $command = $this->scalecmd.' '.$info[0].'x'.$info[1].'! '.$params.' ';
2373 $cropscale = ($data['crs'] ? 'crs-V'.$data['cropV'].'H'.$data['cropH'] : '');
2374
2375 if ($this->alternativeOutputKey) {
2376 $theOutputName = t3lib_div::shortMD5($command.$cropscale.basename($imagefile).$this->alternativeOutputKey.'['.$frame.']');
2377 } else {
2378 $theOutputName = t3lib_div::shortMD5($command.$cropscale.$imagefile.filemtime($imagefile).'['.$frame.']');
2379 }
2380 if ($this->imageMagickConvert_forceFileNameBody) {
2381 $theOutputName = $this->imageMagickConvert_forceFileNameBody;
2382 $this->imageMagickConvert_forceFileNameBody='';
2383 }
2384
2385 // Making the temporary filename:
2386 $this->createTempSubDir('pics/');
2387 $output = $this->absPrefix.$this->tempPath.'pics/'.$this->filenamePrefix.$theOutputName.'.'.$newExt;
2388
2389 // Register temporary filename:
2390 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
2391
2392 if ($this->dontCheckForExistingTempFile || !$this->file_exists_typo3temp_file($output, $imagefile)) {
2393 $this->imageMagickExec($imagefile, $output, $command, $frame);
2394 }
2395 if (file_exists($output)) {
2396 $info[3] = $output;
2397 $info[2] = $newExt;
2398 if ($params) { // params could realisticly change some imagedata!
2399 $info=$this->getImageDimensions($info[3]);
2400 }
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)
2403 }
2404 return $info;
2405 }
2406 }
2407 }
2408 }
2409
2410 /**
2411 * Gets the input image dimensions.
2412 *
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()
2416 */
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)) {
2421 return $returnArr;
2422 } else {
2423 if ($temp = @getImageSize($imageFile)) {
2424 $returnArr = Array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
2425 } else {
2426 $returnArr = $this->imageMagickIdentify($imageFile);
2427 }
2428 if ($returnArr) {
2429 $this->cacheImageDimensions($returnArr);
2430 return $returnArr;
2431 }
2432 }
2433 }
2434 return false;
2435 }
2436
2437 /**
2438 * Cache the result of the getImageDimensions function into the database. Does not check if the
2439 * file exists!
2440 *
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>
2444 */
2445 function cacheImageDimensions($identifyResult) {
2446 global $TYPO3_DB;
2447 // Create a md5 hash of the filename
2448 $md5Hash = md5_file($identifyResult[3]);
2449 if ($md5Hash) {
2450 $fieldArr = array (
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],
2457 );
2458 $TYPO3_DB->exec_INSERTquery('cache_imagesizes', $fieldArr);
2459 if (!$err = $TYPO3_DB->sql_error()) {
2460 return true;
2461 }
2462 }
2463 return false;
2464 }
2465
2466 /**
2467 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
2468 *
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>
2472 */
2473 function getCachedImageDimensions($imageFile) {
2474 global $TYPO3_DB;
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'));
2479 if ($res) {
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'));
2484 } else {
2485 return (array((int) $row['imagewidth'], (int) $row['imageheight'], strtolower($reg[0]), $imageFile));
2486 }
2487 }
2488 }
2489 return false;
2490 }
2491
2492 /**
2493 * Get numbers for scaling the image based on input
2494 *
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"
2499 * @return array
2500 * @access private
2501 * @see imageMagickConvert()
2502 */
2503 function getImageScale($info,$w,$h,$options) {
2504 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
2505
2506 if (strstr($w.$h, 'c')) {
2507 $out['cropH'] = intval(substr(strstr($w, 'c'), 1));
2508 $out['cropV'] = intval(substr(strstr($h, 'c'), 1));
2509 $crs = true;
2510 } else {
2511 $crs = false;
2512 }
2513 $out['crs'] = $crs;
2514
2515 $w=intval($w);
2516 $h=intval($h);
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
2523 }
2524 } else {
2525 if ($info[0]>$options['maxW']) {
2526 $w=$options['maxW'];
2527 $max=1; // height should follow
2528 }
2529 }
2530 }
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
2536 }
2537 } else {
2538 if ($info[1]>$options['maxH']) { // Changed [0] to [1] 290801
2539 $h=$options['maxH'];
2540 $max=1; // height should follow
2541 }
2542 }
2543 }
2544 $out['origW']=$w;
2545 $out['origH']=$h;
2546 $out['max'] = $max;
2547
2548 if (!$this->mayScaleUp) {
2549 if ($w>$info[0]){$w=$info[0];}
2550 if ($h>$info[1]){$h=$info[1];}
2551 }
2552 if ($w || $h) { // if scaling should be performed
2553 if ($w && !$h) {
2554 $info[1] = ceil($info[1]*($w/$info[0]));
2555 $info[0] = $w;
2556 }
2557 if (!$w && $h) {
2558 $info[0] = ceil($info[0]*($h/$info[1]));
2559 $info[1] = $h;
2560 }
2561 if ($w && $h) {
2562 if ($max) {
2563 $ratio = $info[0]/$info[1];
2564 if ($h*$ratio > $w) {
2565 $h = round($w/$ratio);
2566 } else {
2567 $w = round($h*$ratio);
2568 }
2569 }
2570 if ($crs) {
2571 $ratio = $info[0] / $info[1];
2572 if ($h * $ratio < $w) {
2573 $h = round($w / $ratio);
2574 } else {
2575 $w = round($h * $ratio);
2576 }
2577 }
2578 $info[0] = $w;
2579 $info[1] = $h;
2580 }
2581 }
2582 $out[0]=$info[0];
2583 $out[1]=$info[1];
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]);
2588 }
2589 $out[0]=$options['minW'];
2590 }
2591 if ($options['minH'] && $out[1]<$options['minH']) {
2592 if (($max || $crs) && $out[1]) {
2593 $out[0]= round($out[0]*$options['minH']/$out[1]);
2594 }
2595 $out[1]=$options['minH'];
2596 }
2597
2598 return $out;
2599 }
2600
2601 /**
2602 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2603 *
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"
2607 * @access private
2608 */
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
2612 return 1;
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(
2616 'md5hash',
2617 'cache_typo3temp_log',
2618 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log') . ' AND tstamp>' . ($GLOBALS['EXEC_TIME'] - 30)
2619 );
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.
2625
2626 $insertFields = array(
2627 'md5hash' => $md5Hash,
2628 'tstamp' => $GLOBALS['EXEC_TIME'],
2629 'filename' => $output,
2630 'orig_filename' => $orig
2631 );
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);
2634
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);
2636 return 0;
2637 }
2638 }
2639 } else {
2640 return file_exists($output);
2641 }
2642 }
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661 /***********************************
2662 *
2663 * ImageMagick API functions
2664 *
2665 ***********************************/
2666
2667 /**
2668 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2669 * Using ImageMagick
2670 *
2671 * @param string The relative (to PATH_site) image filepath
2672 * @return array
2673 */
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]);
2682 if ($splitstring) {
2683 preg_match('/([^\.]*)$/',$imagefile,$reg);
2684 $splitinfo = explode(' ', $splitstring);
2685 foreach ($splitinfo as $key => $val) {
2686 $temp = '';
2687 if ($val) {$temp = explode('x', $val);}
2688 if (intval($temp[0]) && intval($temp[1])) {
2689 $dim=$temp;
2690 break;
2691 }
2692 }
2693 if ($dim[0] && $dim[1]) {
2694 return Array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2695 }
2696 }
2697 }
2698 }
2699
2700 /**
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.
2703 *
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()"
2710 */
2711 function imageMagickExec($input, $output, $params, $frame = 0) {
2712 if (!$this->NO_IMAGE_MAGICK) {
2713
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) . ']';
2718 } else {
2719 $frame = '';
2720 }
2721
2722 $cmd = t3lib_div::imageMagickCommand('convert', $params . ' ' . $this->wrapFileName($input) . $frame . ' ' . $this->wrapFileName($output));
2723 $this->IM_commands[] = array($output,$cmd);
2724
2725 $ret = exec($cmd);
2726 t3lib_div::fixPermissions($output); // Change the permissions of the file
2727
2728 return $ret;
2729 }
2730 }
2731
2732 /**
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.
2735 *
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: ...
2741 * @return void
2742 */
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;
2749 }
2750 }
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);
2755
2756 $ret = exec($cmd);
2757 t3lib_div::fixPermissions($output); // Change the permissions of the file
2758
2759 if (is_file($theMask)) {
2760 @unlink($theMask);
2761 }
2762
2763 return $ret;
2764 }
2765 }
2766
2767 /**
2768 * Escapes a file name so it can safely be used on the command line.
2769 *
2770 * @param string $inputName filename to safeguard, must not be empty
2771 *
2772 * @return string $inputName escaped as needed
2773 */
2774 protected function wrapFileName($inputName) {
2775 return escapeshellarg($inputName);
2776 }
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800 /***********************************
2801 *
2802 * Various IO functions
2803 *
2804 ***********************************/
2805
2806 /**
2807 * Returns true if the input file existed
2808 *
2809 * @param string Input file to check
2810 * @return string Returns the filename if the file existed, otherwise empty.
2811 */
2812 function checkFile($file) {
2813 if (@is_file($file)) {
2814 return $file;
2815 } else {
2816 return '';
2817 }
2818 }
2819
2820 /**
2821 * Creates subdirectory in typo3temp/ if not already found.
2822 *
2823 * @param string Name of sub directory
2824 * @return boolean Result of t3lib_div::mkdir(), true if it went well.
2825 */
2826 function createTempSubDir($dirName) {
2827
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;
2831 } else {
2832 $tmpPath = PATH_site.$this->tempPath;
2833 }
2834
2835 // Making the temporary filename:
2836 if (!@is_dir($tmpPath.$dirName)) {
2837 return t3lib_div::mkdir($tmpPath.$dirName);
2838 }
2839 }
2840
2841 /**
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.
2843 *
2844 * @param pointer The image pointer (reference)
2845 * @param string The ImageMagick parameters. Like effects, scaling etc.
2846 * @return void
2847 */
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);
2854 if ($tmpImg) {
2855 ImageDestroy($im);
2856 $im = $tmpImg;
2857 $this->w = imagesx($im);
2858 $this->h = imagesy($im);
2859 }
2860 if (!$this->dontUnlinkTempFiles) {
2861 unlink($theFile);
2862 }
2863 }
2864
2865 /**
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.
2868 *
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.)
2873 */
2874 function gif_or_jpg($type,$w,$h) {
2875 if ($type=='ai' || $w*$h < $this->pixelLimitGif) {
2876 return $this->gifExtension;
2877 } else {
2878 return 'jpg';
2879 }
2880 }
2881
2882 /**
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.
2886 *
2887 * @param string The filename to write to.
2888 * @return string Returns input filename
2889 * @see tslib_gifBuilder::gifBuild()
2890 */
2891 function output($file) {
2892 if ($file) {
2893 $reg = array();
2894 preg_match('/([^\.]*)$/',$file,$reg);
2895 $ext=strtolower($reg[0]);
2896 switch($ext) {
2897 case 'gif':
2898 case 'png':
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));
2903 if ($reduced) {
2904 @copy($reduced, $file);
2905 @unlink($reduced);
2906 }
2907 }
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)
2909 }
2910 break;
2911 case 'jpg':
2912 case 'jpeg':
2913 $quality = 0; // Use the default
2914 if($this->setup['quality']) {
2915 $quality = t3lib_div::intInRange($this->setup['quality'],10,100);
2916 }
2917 if ($this->ImageWrite($this->im, $file, $quality));
2918 break;
2919 }
2920 $GLOBALS['TEMP_IMAGES_ON_PAGE'][]=$file;
2921 }
2922 return $file;
2923 }
2924
2925 /**
2926 * Destroy internal image pointer, $this->im
2927 *
2928 * @return void
2929 * @see tslib_gifBuilder::gifBuild()
2930 */
2931 function destroy() {
2932 ImageDestroy($this->im);
2933 }
2934
2935 /**
2936 * Returns Image Tag for input image information array.
2937 *
2938 * @param array Image information array, key 0/1 is width/height and key 3 is the src value
2939 * @return string Image tag for the input image information array.
2940 */
2941 function imgTag ($imgInfo) {
2942 return '<img src="'.$imgInfo[3].'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'" border="0" alt="" />';
2943 }
2944
2945</