Fixed bug #14443: Deprecate $TYPO3_CONF_VARS[GFX][TTFLocaleConv]
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_stdgraphic.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2009 Kasper Skaarhoj (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 Skaarhoj
32 *
33 * @author Kasper Skaarhoj <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 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
151 * @package TYPO3
152 * @subpackage t3lib
153 * @see tslib_gifBuilder
154 */
155 class t3lib_stdGraphic {
156
157 // Internal configuration, set in init()
158 var $combineScript = 'combine'; // The ImageMagick filename used for combining two images. This name changed during the versions.
159 var $noFramePrepended=0; // If set, there is no frame pointer prepended to the filenames.
160 var $GD2=0; // Set, if the GDlib used is version 2.
161 var $imagecopyresized_fix=0; // If set, imagecopyresized will not be called directly. For GD2 (some PHP installs?)
162 var $gifExtension = 'gif'; // This should be changed to 'png' if you want this class to read/make PNG-files instead!
163 var $gdlibExtensions = ''; // File formats supported by gdlib. This variable get's filled in "init" method
164 var $truecolor = true; // Internal variable which get's used to determine wheter GDlib should use function truecolor pendants
165 var $png_truecolor = false; // Set to true if generated png's should be truecolor by default
166 var $truecolorColors = 0xffffff; // 16777216 Colors is the maximum value for PNG, JPEG truecolor images (24-bit, 8-bit / Channel)
167 var $TTFLocaleConv = ''; // Used to recode input to TTF-functions for other charsets. Deprecated since TYPO3 3.6, will be removed in TYPO3 4.6
168 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.
169 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!
170 var $webImageExt = 'gif,jpg,jpeg,png'; // Commalist of web image extensions (can be shown by a webbrowser)
171 var $maskNegate = ''; // Will be ' -negate' if ImageMagick ver 5.2+. See init();
172 var $NO_IM_EFFECTS = '';
173 var $cmds = Array (
174 'jpg' => '',
175 'jpeg' => '',
176 'gif' => '-colors 64',
177 'png' => '-colors 64'
178 );
179 var $NO_IMAGE_MAGICK = '';
180 var $V5_EFFECTS = 0;
181 var $im_version_4 = 0;
182 var $mayScaleUp = 1;
183
184 // Variables for testing, alternative usage etc.
185 var $filenamePrefix=''; // Filename prefix for images scaled in imageMagickConvert()
186 var $imageMagickConvert_forceFileNameBody=''; // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
187 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.
188 var $dontCompress=0; // Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
189 var $dontUnlinkTempFiles=0; // For debugging ONLY!
190 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...
191
192 // Internal:
193 var $IM_commands = Array(); // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
194 var $workArea = Array();
195
196 // Constants:
197 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.
198 var $absPrefix = ''; // Prefix for relative paths. Used in "show_item.php" script. Is prefixed the output file name IN imageMagickConvert()
199 var $scalecmd = '-geometry'; // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
200 var $im5fx_blurSteps='1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5'; // Used by v5_blur() to simulate 10 continuous steps of blurring
201 var $im5fx_sharpenSteps='1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5'; // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
202 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
203 var $colMap = Array ( // Array mapping HTML color names to RGB values.
204 'aqua' => Array(0,255,255),
205 'black' => Array(0,0,0),
206 'blue' => Array(0,0,255),
207 'fuchsia' => Array(255,0,255),
208 'gray' => Array(128,128,128),
209 'green' => Array(0,128,0),
210 'lime' => Array(0,255,0),
211 'maroon' => Array(128,0,0),
212 'navy' => Array(0,0,128),
213 'olive' => Array(128,128,0),
214 'purple' => Array(128,0,128),
215 'red' => Array(255,0,0),
216 'silver' => Array(192,192,192),
217 'teal' => Array(0,128,128),
218 'yellow' => Array(255,255,0),
219 'white' => Array(255,255,255)
220 );
221
222 /**
223 * Charset conversion object:
224 *
225 * @var t3lib_cs
226 */
227 var $csConvObj;
228 var $nativeCharset=''; // Is set to the native character set of the input strings.
229
230
231
232
233
234 /**
235 * Init function. Must always call this when using the class.
236 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
237 *
238 * @return void
239 */
240 function init() {
241 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
242
243 if (function_exists('imagecreatefromjpeg')&&function_exists('imagejpeg')) {
244 $this->gdlibExtensions .= ',jpg,jpeg';
245 }
246 if (function_exists('imagecreatefrompng')&&function_exists('imagepng')) {
247 $this->gdlibExtensions .= ',png';
248 }
249 if (function_exists('imagecreatefromgif')&&function_exists('imagegif')) {
250 $this->gdlibExtensions .= ',gif';
251 }
252 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['png_truecolor']) {
253 $this->png_truecolor = true;
254 }
255 if (!$gfxConf['gdlib_2'] || !function_exists('imagecreatetruecolor')) {
256 $this->truecolor = false;
257 }
258 if (!$gfxConf['im_version_5']) {
259 $this->im_version_4 = true;
260 }
261
262 // When GIFBUILDER gets used in truecolor mode (GD2 required)
263 if ($this->truecolor) {
264 if ($this->png_truecolor) {
265 $this->cmds['png'] = ''; // No colors parameter if we generate truecolor images.
266 }
267 $this->cmds['gif'] = ''; // No colors parameter if we generate truecolor images.
268 }
269
270 // Setting default JPG parameters:
271 $this->jpegQuality = t3lib_div::intInRange($gfxConf['jpg_quality'], 10, 100, 75);
272 $this->cmds['jpg'] = $this->cmds['jpeg'] = '-colorspace RGB -sharpen 50 -quality '.$this->jpegQuality;
273
274 if ($gfxConf['im_combine_filename']) $this->combineScript=$gfxConf['im_combine_filename'];
275 if ($gfxConf['im_noFramePrepended']) $this->noFramePrepended=1;
276
277 if ($gfxConf['gdlib_2']) {
278 $this->GD2 = 1;
279 $this->imagecopyresized_fix = $gfxConf['gdlib_2']==='no_imagecopyresized_fix' ? 0 : 1;
280 }
281 if ($gfxConf['gdlib_png']) {
282 $this->gifExtension='png';
283 }
284 if ($gfxConf['TTFLocaleConv']) {
285 $this->TTFLocaleConv = $gfxConf['TTFLocaleConv'];
286 }
287 if ($gfxConf['enable_typo3temp_db_tracking']) {
288 $this->enable_typo3temp_db_tracking = $gfxConf['enable_typo3temp_db_tracking'];
289 }
290
291 $this->imageFileExt = $gfxConf['imagefile_ext'];
292
293 // This should be set if ImageMagick ver. 5+ is used.
294 if ($gfxConf['im_negate_mask']) {
295 // Boolean. Indicates if the mask images should be inverted first.
296 // This depends of the ImageMagick version. Below ver. 5.1 this should be false.
297 // Above ImageMagick version 5.2+ it should be true.
298 // Just set the flag if the masks works opposite the intension!
299 $this->maskNegate = ' -negate';
300 }
301 if ($gfxConf['im_no_effects']) {
302 // Boolean. This is necessary if using ImageMagick 5+.
303 // Approved version for using effects is version 4.2.9.
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 = $this->imagecreate($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 = $this->imagecreate($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 = $this->imagecreate(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 = $this->imagecreate($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 = $this->imagecreate($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 $word = $word;
914 $wordInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $word, $splitRenderingConf ,$sF);
915 $wordW = ($wordInf[2]-$wordInf[0]);
916 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $word, $splitRenderingConf, $sF);
917 $x+=$wordW+$wordSpacing;
918 }
919 } else {
920 $utf8Chars = $this->singleChars($text);
921 // For each UTF-8 char, do:
922 foreach($utf8Chars as $char) {
923 $charInf = $this->ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $char, $splitRenderingConf, $sF);
924 $charW = ($charInf[2]-$charInf[0]);
925 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $char, $splitRenderingConf, $sF);
926 $x+=$charW+(($char==' ')?$wordSpacing:$spacing);
927 }
928 }
929 }
930
931 /**
932 * Function that finds the right fontsize that will render the textstring within a certain width
933 *
934 * @param array The TypoScript properties of the TEXT GIFBUILDER object
935 * @return integer The new fontSize
936 * @access private
937 * @author Rene Fritz <r.fritz@colorcube.de>
938 * @see tslib_gifBuilder::start()
939 */
940 function fontResize($conf) {
941 // 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!!!!
942 $maxWidth = intval($conf['maxWidth']);
943 list($spacing,$wordSpacing) = $this->calcWordSpacing($conf);
944 if ($maxWidth) {
945 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
946 return $conf['fontSize'];
947 // ################ no calc for spacing yet !!!!!!
948 } else {
949 do {
950 // determine bounding box.
951 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($conf['text']), $conf['splitRendering.']);
952 if ($conf['angle']< 0) {
953 $pixelWidth = abs($bounds[4]-$bounds[0]);
954 } elseif ($conf['angle'] > 0) {
955 $pixelWidth = abs($bounds[2]-$bounds[6]);
956 } else {
957 $pixelWidth = abs($bounds[4]-$bounds[6]);
958 }
959
960 // Size is fine, exit:
961 if ($pixelWidth <= $maxWidth) {
962 break;
963 } else {
964 $conf['fontSize']--;
965 }
966 } while ($conf['fontSize']>1);
967 }//if spacing
968 }
969 return $conf['fontSize'];
970 }
971
972 /**
973 * Wrapper for ImageTTFBBox
974 *
975 * @param integer (See argument for PHP function ImageTTFBBox())
976 * @param integer (See argument for PHP function ImageTTFBBox())
977 * @param string (See argument for PHP function ImageTTFBBox())
978 * @param string (See argument for PHP function ImageTTFBBox())
979 * @param array Split-rendering configuration
980 * @param integer Scale factor
981 * @return array Information array.
982 */
983 function ImageTTFBBoxWrapper($fontSize, $angle, $fontFile, $string, $splitRendering, $sF=1) {
984
985 // Initialize:
986 $offsetInfo = array();
987 $stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
988
989 // Traverse string parts:
990 foreach($stringParts as $strCfg) {
991 $fontFile = t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']);
992 if (is_readable($fontFile)) {
993
994 // Calculate Bounding Box for part:
995 $calc = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $fontFile, $strCfg['str']);
996
997 // Calculate offsets:
998 if (!count($offsetInfo)) {
999 $offsetInfo = $calc; // First run, just copy over.
1000 } else {
1001 $offsetInfo[2]+=$calc[2]-$calc[0]+intval($splitRendering['compX'])+intval($strCfg['xSpaceBefore'])+intval($strCfg['xSpaceAfter']);
1002 $offsetInfo[3]+=$calc[3]-$calc[1]-intval($splitRendering['compY'])-intval($strCfg['ySpaceBefore'])-intval($strCfg['ySpaceAfter']);
1003 $offsetInfo[4]+=$calc[4]-$calc[6]+intval($splitRendering['compX'])+intval($strCfg['xSpaceBefore'])+intval($strCfg['xSpaceAfter']);
1004 $offsetInfo[5]+=$calc[5]-$calc[7]-intval($splitRendering['compY'])-intval($strCfg['ySpaceBefore'])-intval($strCfg['ySpaceAfter']);
1005 }
1006
1007 } else {
1008 debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFBBoxWrapper()');
1009 }
1010 }
1011
1012 return $offsetInfo;
1013 }
1014
1015 /**
1016 * Wrapper for ImageTTFText
1017 *
1018 * @param pointer (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 integer (See argument for PHP function imageTTFtext())
1024 * @param string (See argument for PHP function imageTTFtext())
1025 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1026 * @param array Split-rendering configuration
1027 * @param integer Scale factor
1028 * @return void
1029 */
1030 function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering,$sF=1) {
1031
1032 // Initialize:
1033 $stringParts = $this->splitString($string,$splitRendering,$fontSize,$fontFile);
1034 $x = ceil($sF*$x);
1035 $y = ceil($sF*$y);
1036
1037 // Traverse string parts:
1038 foreach($stringParts as $i => $strCfg) {
1039
1040 // Initialize:
1041 $colorIndex = $color;
1042
1043 // Set custom color if any (only when niceText is off):
1044 if ($strCfg['color'] && $sF==1) {
1045 $cols = $this->convertColor($strCfg['color']);
1046 $colorIndex = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
1047 $colorIndex = $color >= 0 ? $colorIndex : -$colorIndex;
1048 }
1049
1050 // Setting xSpaceBefore
1051 if ($i) {
1052 $x+= intval($strCfg['xSpaceBefore']);
1053 $y-= intval($strCfg['ySpaceBefore']);
1054 }
1055
1056 $fontFile = t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']);
1057 if (is_readable($fontFile)) {
1058
1059 // Render part:
1060 ImageTTFText($im, t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']);
1061
1062 // Calculate offset to apply:
1063 $wordInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$strCfg['fontSize']), $angle, t3lib_stdGraphic::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']);
1064 $x+= $wordInf[2]-$wordInf[0]+intval($splitRendering['compX'])+intval($strCfg['xSpaceAfter']);
1065 $y+= $wordInf[5]-$wordInf[7]-intval($splitRendering['compY'])-intval($strCfg['ySpaceAfter']);
1066
1067 } else {
1068 debug('cannot read file: '.$fontFile, 't3lib_stdGraphic::ImageTTFTextWrapper()');
1069 }
1070
1071 }
1072 }
1073
1074 /**
1075 * Splitting a string for ImageTTFBBox up into an array where each part has its own configuration options.
1076 *
1077 * @param string UTF-8 string
1078 * @param array Split-rendering configuration from GIFBUILDER TEXT object.
1079 * @param integer Current fontsize
1080 * @param string Current font file
1081 * @return array Array with input string splitted according to configuration
1082 */
1083 function splitString($string,$splitRendering,$fontSize,$fontFile) {
1084
1085 // Initialize by setting the whole string and default configuration as the first entry.
1086 $result = array();
1087 $result[] = array(
1088 'str' => $string,
1089 'fontSize' => $fontSize,
1090 'fontFile' => $fontFile
1091 );
1092
1093 // Traverse the split-rendering configuration:
1094 // Splitting will create more entries in $result with individual configurations.
1095 if (is_array($splitRendering)) {
1096 $sKeyArray = t3lib_TStemplate::sortedKeyList($splitRendering);
1097
1098 // Traverse configured options:
1099 foreach($sKeyArray as $key) {
1100 $cfg = $splitRendering[$key.'.'];
1101
1102 // Process each type of split rendering keyword:
1103 switch((string)$splitRendering[$key]) {
1104 case 'highlightWord':
1105 if (strlen($cfg['value'])) {
1106 $newResult = array();
1107
1108 // Traverse the current parts of the result array:
1109 foreach($result as $part) {
1110 // Explode the string value by the word value to highlight:
1111 $explodedParts = explode($cfg['value'],$part['str']);
1112 foreach($explodedParts as $c => $expValue) {
1113 if (strlen($expValue)) {
1114 $newResult[] = array_merge($part,array('str' => $expValue));
1115 }
1116 if ($c+1 < count($explodedParts)) {
1117 $newResult[] = array(
1118 'str' => $cfg['value'],
1119 'fontSize' => $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1120 'fontFile' => $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1121 'color' => $cfg['color'],
1122 'xSpaceBefore' => $cfg['xSpaceBefore'],
1123 'xSpaceAfter' => $cfg['xSpaceAfter'],
1124 'ySpaceBefore' => $cfg['ySpaceBefore'],
1125 'ySpaceAfter' => $cfg['ySpaceAfter'],
1126 );
1127 }
1128 }
1129 }
1130
1131 // Set the new result as result array:
1132 if (count($newResult)) {
1133 $result = $newResult;
1134 }
1135 }
1136 break;
1137 case 'charRange':
1138 if (strlen($cfg['value'])) {
1139
1140 // Initialize range:
1141 $ranges = t3lib_div::trimExplode(',',$cfg['value'],1);
1142 foreach($ranges as $i => $rangeDef) {
1143 $ranges[$i] = t3lib_div::intExplode('-',$ranges[$i]);
1144 if (!isset($ranges[$i][1])) $ranges[$i][1] = $ranges[$i][0];
1145 }
1146 $newResult = array();
1147
1148 // Traverse the current parts of the result array:
1149 foreach($result as $part) {
1150
1151 // Initialize:
1152 $currentState = -1;
1153 $bankAccum = '';
1154
1155 // Explode the string value by the word value to highlight:
1156 $utf8Chars = $this->singleChars($part['str']);
1157 foreach($utf8Chars as $utfChar) {
1158
1159 // Find number and evaluate position:
1160 $uNumber = $this->csConvObj->utf8CharToUnumber($utfChar);
1161 $inRange = 0;
1162 foreach($ranges as $rangeDef) {
1163 if ($uNumber >= $rangeDef[0] && (!$rangeDef[1] || $uNumber <= $rangeDef[1])) {
1164 $inRange = 1;
1165 break;
1166 }
1167 }
1168 if ($currentState==-1) $currentState = $inRange; // Initialize first char
1169
1170 // Switch bank:
1171 if ($inRange != $currentState && !t3lib_div::inList('32,10,13,9',$uNumber)) {
1172
1173 // Set result:
1174 if (strlen($bankAccum)) {
1175 $newResult[] = array(
1176 'str' => $bankAccum,
1177 'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1178 'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1179 'color' => $currentState ? $cfg['color'] : '',
1180 'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
1181 'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
1182 'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
1183 'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : '',
1184 );
1185 }
1186
1187 // Initialize new settings:
1188 $currentState = $inRange;
1189 $bankAccum = '';
1190 }
1191
1192 // Add char to bank:
1193 $bankAccum.=$utfChar;
1194 }
1195
1196 // Set result for FINAL part:
1197 if (strlen($bankAccum)) {
1198 $newResult[] = array(
1199 'str' => $bankAccum,
1200 'fontSize' => $currentState && $cfg['fontSize'] ? $cfg['fontSize'] : $part['fontSize'],
1201 'fontFile' => $currentState && $cfg['fontFile'] ? $cfg['fontFile'] : $part['fontFile'],
1202 'color' => $currentState ? $cfg['color'] : '',
1203 'xSpaceBefore' => $currentState ? $cfg['xSpaceBefore'] : '',
1204 'xSpaceAfter' => $currentState ? $cfg['xSpaceAfter'] : '',
1205 'ySpaceBefore' => $currentState ? $cfg['ySpaceBefore'] : '',
1206 'ySpaceAfter' => $currentState ? $cfg['ySpaceAfter'] : '',
1207 );
1208 }
1209 }
1210
1211 // Set the new result as result array:
1212 if (count($newResult)) {
1213 $result = $newResult;
1214 }
1215 }
1216 break;
1217 }
1218 }
1219 }
1220
1221 return $result;
1222 }
1223
1224 /**
1225 * Calculates the spacing and wordSpacing values
1226 *
1227 * @param array TypoScript array for the TEXT GIFBUILDER object
1228 * @param integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1229 * @return array Array with two keys [0]/[1] being array($spacing,$wordSpacing)
1230 * @access private
1231 * @see calcBBox()
1232 */
1233 function calcWordSpacing($conf, $scaleFactor=1) {
1234
1235 $spacing = intval($conf['spacing']);
1236 $wordSpacing = intval($conf['wordSpacing']);
1237 $wordSpacing = $wordSpacing?$wordSpacing:$spacing*2;
1238
1239 $spacing*=$scaleFactor;
1240 $wordSpacing*=$scaleFactor;
1241
1242 return array($spacing,$wordSpacing);
1243 }
1244
1245 /**
1246 * Calculates and returns the niceText.scaleFactor
1247 *
1248 * @param array TypoScript array for the TEXT GIFBUILDER object
1249 * @return integer TypoScript value from eg $conf['niceText.']['scaleFactor']
1250 * @access private
1251 */
1252 function getTextScalFactor($conf) {
1253 if (!$conf['niceText']) {
1254 $sF = 1;
1255 } else { // NICETEXT::
1256 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
1257 }
1258 return $sF;
1259 }
1260
1261 /**
1262 * Renders a regular text and takes care of a possible line break automatically.
1263 *
1264 * @param pointer (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 integer (See argument for PHP function imageTTFtext())
1270 * @param string (See argument for PHP function imageTTFtext())
1271 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
1272 * @param array Split-rendering configuration
1273 * @param integer Scale factor
1274 * @param array $conf: The configuration
1275 * @return void
1276 */
1277 protected function renderTTFText(&$im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $conf, $sF = 1) {
1278 if (isset($conf['breakWidth']) && $conf['breakWidth'] && $this->getRenderedTextWidth($string, $conf) > $conf['breakWidth']) {
1279 $phrase = '';
1280 $currentWidth = 0;
1281
1282 $breakWidth = $conf['breakWidth'];
1283 $breakSpace = $this->getBreakSpace($conf);
1284
1285 $wordPairs = $this->getWordPairsForLineBreak($string);
1286 // Iterate through all word pairs:
1287 foreach ($wordPairs as $index => $wordPair) {
1288 $wordWidth = $this->getRenderedTextWidth($wordPair, $conf);
1289 if ($index == 0 || $currentWidth + $wordWidth <= $breakWidth) {
1290 $currentWidth+= $wordWidth;
1291 $phrase.= $wordPair;
1292 } else {
1293 // Render the current phrase that is below breakWidth:
1294 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1295 // Calculate the news height offset:
1296 $y+= $breakSpace;
1297 // Restart the phrase:
1298 $currentWidth = $wordWidth;
1299 $phrase = $wordPair;
1300 }
1301 }
1302 // Render the remaining phrase:
1303 if ($currentWidth) {
1304 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $phrase, $splitRendering, $sF);
1305 }
1306 } else {
1307 $this->ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF);
1308 }
1309 }
1310
1311 /**
1312 * Gets the word pairs used for automatic line breaks.
1313 *
1314 * @param string $string
1315 * @return array
1316 */
1317 protected function getWordPairsForLineBreak($string) {
1318 $wordPairs = array();
1319
1320 $wordsArray = preg_split('#([ -.,!:]+)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
1321 $wordsCount = count($wordsArray);
1322 for ($index=0; $index < $wordsCount; $index+= 2) {
1323 $wordPairs[] = $wordsArray[$index] . $wordsArray[$index + 1];
1324 }
1325
1326 return $wordPairs;
1327 }
1328
1329 /**
1330 * Gets the rendered text width.
1331 *
1332 * @param string $text
1333 * @param array $conf
1334 * @param integer
1335 */
1336 protected function getRenderedTextWidth($text, $conf) {
1337 $bounds = $this->ImageTTFBBoxWrapper($conf['fontSize'], $conf['angle'], $conf['fontFile'], $this->recodeString($text), $conf['splitRendering.']);
1338 if ($conf['angle']< 0) {
1339 $pixelWidth = abs($bounds[4]-$bounds[0]);
1340 } elseif ($conf['angle'] > 0) {
1341 $pixelWidth = abs($bounds[2]-$bounds[6]);
1342 } else {
1343 $pixelWidth = abs($bounds[4]-$bounds[6]);
1344 }
1345 return $pixelWidth;
1346 }
1347
1348 /**
1349 * Gets the break space for each new line.
1350 *
1351 * @param array $conf: TypoScript configuration for the currently rendered object
1352 * @param array $boundingBox: The bounding box the the currently rendered object
1353 * @return integer The break space
1354 */
1355 protected function getBreakSpace($conf, array $boundingBox = NULL) {
1356 if (!isset($boundingBox)) {
1357 $boundingBox = $this->calcBBox($conf);
1358 $boundingBox = $boundingBox[2];
1359 }
1360
1361 if (isset($conf['breakSpace']) && $conf['breakSpace']) {
1362 $breakSpace = $boundingBox['lineHeight'] * $conf['breakSpace'];
1363 } else {
1364 $breakSpace = $boundingBox['lineHeight'];
1365 }
1366
1367 return $breakSpace;
1368 }
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380 /*********************************************
1381 *
1382 * Other GIFBUILDER objects related to TEXT
1383 *
1384 *********************************************/
1385
1386 /**
1387 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
1388 *
1389 * @param pointer GDlib image pointer
1390 * @param array TypoScript array with configuration for the GIFBUILDER object.
1391 * @param array The current working area coordinates.
1392 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1393 * @return void
1394 * @see tslib_gifBuilder::make(), makeText()
1395 */
1396 function makeOutline(&$im,$conf,$workArea,$txtConf) {
1397 $thickness = intval($conf['thickness']);
1398 if ($thickness) {
1399 $txtConf['fontColor'] = $conf['color'];
1400 $outLineDist = t3lib_div::intInRange($thickness,1,2);
1401 for ($b=1;$b<=$outLineDist;$b++) {
1402 if ($b==1) {
1403 $it = 8;
1404 } else {
1405 $it = 16;
1406 }
1407 $outL = $this->circleOffset($b, $it);
1408 for ($a=0;$a<$it;$a++) {
1409 $this->makeText($im,$txtConf,$this->applyOffset($workArea,$outL[$a]));
1410 }
1411 }
1412 }
1413 }
1414
1415 /**
1416 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
1417 *
1418 * access private
1419 *
1420 * @param integer Distance
1421 * @param integer Iterations.
1422 * @return array
1423 * @see makeOutline()
1424 */
1425 function circleOffset($distance, $iterations) {
1426 $res = Array();
1427 if ($distance && $iterations) {
1428 for ($a=0;$a<$iterations;$a++) {
1429 $yOff = round(sin(2*pi()/$iterations*($a+1))*100*$distance);
1430 if ($yOff) {$yOff = intval(ceil(abs($yOff/100))*($yOff/abs($yOff)));}
1431 $xOff = round(cos(2*pi()/$iterations*($a+1))*100*$distance);
1432 if ($xOff) {$xOff = intval(ceil(abs($xOff/100))*($xOff/abs($xOff)));}
1433 $res[$a] = Array($xOff,$yOff);
1434 }
1435 }
1436 return $res;
1437 }
1438
1439 /**
1440 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
1441 *
1442 * @param pointer GDlib image pointer
1443 * @param array TypoScript array with configuration for the GIFBUILDER object.
1444 * @param array The current working area coordinates.
1445 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1446 * @return void
1447 * @see tslib_gifBuilder::make(), makeShadow()
1448 */
1449 function makeEmboss(&$im,$conf,$workArea,$txtConf) {
1450 $conf['color']=$conf['highColor'];
1451 $this->makeShadow($im,$conf,$workArea,$txtConf);
1452 $newOffset = t3lib_div::intExplode(',',$conf['offset']);
1453 $newOffset[0]*=-1;
1454 $newOffset[1]*=-1;
1455 $conf['offset']=implode(',',$newOffset);
1456 $conf['color']=$conf['lowColor'];
1457 $this->makeShadow($im,$conf,$workArea,$txtConf);
1458 }
1459
1460 /**
1461 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
1462 * The operation involves ImageMagick for combining.
1463 *
1464 * @param pointer GDlib image pointer
1465 * @param array TypoScript array with configuration for the GIFBUILDER object.
1466 * @param array The current working area coordinates.
1467 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
1468 * @return void
1469 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
1470 */
1471 function makeShadow(&$im,$conf,$workArea,$txtConf) {
1472 $workArea = $this->applyOffset($workArea,t3lib_div::intExplode(',',$conf['offset']));
1473 $blurRate = t3lib_div::intInRange(intval($conf['blur']),0,99);
1474
1475 if (!$blurRate || $this->NO_IM_EFFECTS) { // No effects if ImageMagick ver. 5+
1476 $txtConf['fontColor'] = $conf['color'];
1477 $this->makeText($im,$txtConf,$workArea);
1478 } else {
1479 $w = imagesx($im);
1480 $h = imagesy($im);
1481 $blurBorder= 3; // area around the blur used for cropping something
1482 $tmpStr = $this->randomName();
1483 $fileMenu = $tmpStr.'_menu.'.$this->gifExtension;
1484 $fileColor = $tmpStr.'_color.'.$this->gifExtension;
1485 $fileMask = $tmpStr.'_mask.'.$this->gifExtension;
1486
1487 // BlurColor Image laves
1488 $blurColImg = $this->imagecreate($w,$h);
1489 $bcols=$this->convertColor($conf['color']);
1490 $Bcolor = ImageColorAllocate($blurColImg, $bcols[0],$bcols[1],$bcols[2]);
1491 ImageFilledRectangle($blurColImg, 0, 0, $w, $h, $Bcolor);
1492 $this->ImageWrite($blurColImg, $fileColor);
1493 ImageDestroy($blurColImg);
1494
1495 // The mask is made: BlurTextImage
1496 $blurTextImg = $this->imagecreate($w+$blurBorder*2,$h+$blurBorder*2);
1497 $Bcolor = ImageColorAllocate($blurTextImg, 0,0,0); // black background
1498 ImageFilledRectangle($blurTextImg, 0, 0, $w+$blurBorder*2, $h+$blurBorder*2, $Bcolor);
1499 $txtConf['fontColor'] = 'white';
1500 $blurBordArr = Array($blurBorder,$blurBorder);
1501 $this->makeText($blurTextImg,$txtConf, $this->applyOffset($workArea,$blurBordArr));
1502 $this->ImageWrite($blurTextImg, $fileMask); // dump to temporary file
1503 ImageDestroy($blurTextImg); // destroy
1504
1505
1506 $command='';
1507 $command.=$this->maskNegate;
1508
1509 if ($this->V5_EFFECTS) {
1510 $command.=$this->v5_blur($blurRate+1);
1511 } else {
1512 // Blurring of the mask
1513 $times = ceil($blurRate/10); // How many blur-commands that is executed. Min = 1;
1514 $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.
1515 $newBlurRate = t3lib_div::intInRange($newBlurRate,1,99);
1516 for ($a=0;$a<$times;$a++) { // Building blur-command
1517 $command.=' -blur '.$blurRate;
1518 }
1519 }
1520
1521 $this->imageMagickExec($fileMask,$fileMask,$command.' +matte');
1522
1523 $blurTextImg_tmp = $this->imageCreateFromFile($fileMask); // the mask is loaded again
1524 if ($blurTextImg_tmp) { // if nothing went wrong we continue with the blurred mask
1525
1526 // cropping the border from the mask
1527 $blurTextImg = $this->imagecreate($w,$h);
1528 $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
1529 ImageDestroy($blurTextImg_tmp); // Destroy the temporary mask
1530
1531 // adjust the mask
1532 $intensity = 40;
1533 if ($conf['intensity']) {
1534 $intensity = t3lib_div::intInRange($conf['intensity'],0,100);
1535 }
1536 $intensity = ceil(255-($intensity/100*255));
1537 $this->inputLevels($blurTextImg,0,$intensity,$this->maskNegate);
1538
1539 $opacity = t3lib_div::intInRange(intval($conf['opacity']),0,100);
1540 if ($opacity && $opacity<100) {
1541 $high = ceil(255*$opacity/100);
1542 $this->outputLevels($blurTextImg,0,$high,$this->maskNegate); // reducing levels as the opacity demands
1543 }
1544
1545 $this->ImageWrite($blurTextImg, $fileMask); // Dump the mask again
1546 ImageDestroy($blurTextImg); // Destroy the mask
1547
1548 // The pictures are combined
1549 $this->ImageWrite($im, $fileMenu); // The main pictures is saved temporarily
1550
1551 $this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);
1552
1553 $backIm = $this->imageCreateFromFile($fileMenu); // The main image is loaded again...
1554 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
1555 ImageColorTransparent($backIm,-1);
1556 $im = $backIm;
1557 }
1558 }
1559 // Deleting temporary files;
1560 if (!$this->dontUnlinkTempFiles) {
1561 unlink($fileMenu);
1562 unlink($fileColor);
1563 unlink($fileMask);
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 *
1590 * Other GIFBUILDER objects
1591 *
1592 ****************************/
1593
1594 /**
1595 * Implements the "BOX" GIFBUILDER object
1596 *
1597 * @param pointer GDlib image pointer
1598 * @param array TypoScript array with configuration for the GIFBUILDER object.
1599 * @param array The current working area coordinates.
1600 * @return void
1601 * @see tslib_gifBuilder::make()
1602 */
1603 function makeBox(&$im,$conf,$workArea) {
1604 $cords = t3lib_div::intExplode(',',$conf['dimensions'].',,,');
1605 $conf['offset']=$cords[0].','.$cords[1];
1606 $cords = $this->objPosition($conf,$workArea,Array($cords[2],$cords[3]));
1607 $cols=$this->convertColor($conf['color']);
1608 if (!$this->truecolor) {
1609 $reduce = t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256);
1610 $this->reduceColors($im, $reduce-1, $reduce-2); // If "reduce-1" colors (or more) are used reduce them to "reduce-2"
1611 }
1612
1613 $opacity = 0;
1614 if (isset($conf['opacity'])) {
1615 // conversion:
1616 // PHP 0 = opaque, 127 = transparent
1617 // TYPO3 100 = opaque, 0 = transparent
1618 $opacity = t3lib_div::intInRange(intval($conf['opacity']), 1, 100, 1);
1619 $opacity = abs($opacity - 100);
1620 $opacity = round((127 * $opacity) / 100);
1621 }
1622
1623 $tmpColor = ImageColorAllocateAlpha($im, $cols[0],$cols[1],$cols[2], $opacity);
1624 imagefilledrectangle($im, $cords[0], $cords[1], $cords[0]+$cords[2]-1, $cords[1]+$cords[3]-1, $tmpColor);
1625 }
1626
1627 /**
1628 * Implements the "EFFECT" GIFBUILDER object
1629 * The operation involves ImageMagick for applying effects
1630 *
1631 * @param pointer GDlib image pointer
1632 * @param array TypoScript array with configuration for the GIFBUILDER object.
1633 * @return void
1634 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
1635 */
1636 function makeEffect(&$im, $conf) {
1637 $commands = $this->IMparams($conf['value']);
1638 if ($commands) {
1639 $this->applyImageMagickToPHPGif($im, $commands);
1640 }
1641 }
1642
1643 /**
1644 * Creating ImageMagick paramters from TypoScript property
1645 *
1646 * @param string A string with effect keywords=value pairs separated by "|"
1647 * @return string ImageMagick prepared parameters.
1648 * @access private
1649 * @see makeEffect()
1650 */
1651 function IMparams($setup) {
1652 if (!trim($setup)){return '';}
1653 $effects = explode('|', $setup);
1654 $commands = '';
1655 foreach ($effects as $val) {
1656 $pairs=explode('=',$val,2);
1657 $value = trim($pairs[1]);
1658 $effect = strtolower(trim($pairs[0]));
1659 switch($effect) {
1660 case 'gamma':
1661 $commands.=' -gamma '.doubleval($value);
1662 break;
1663 case 'blur':
1664 if (!$this->NO_IM_EFFECTS) {
1665 if ($this->V5_EFFECTS) {
1666 $commands.=$this->v5_blur($value);
1667 } else {
1668 $commands.=' -blur '.t3lib_div::intInRange($value,1,99);
1669 }
1670 }
1671 break;
1672 case 'sharpen':
1673 if (!$this->NO_IM_EFFECTS) {
1674 if ($this->V5_EFFECTS) {
1675 $commands.=$this->v5_sharpen($value);
1676 } else {
1677 $commands.=' -sharpen '.t3lib_div::intInRange($value,1,99);
1678 }
1679 }
1680 break;
1681 case 'rotate':
1682 $commands.=' -rotate '.t3lib_div::intInRange($value,0,360);
1683 break;
1684 case 'solarize':
1685 $commands.=' -solarize '.t3lib_div::intInRange($value,0,99);
1686 break;
1687 case 'swirl':
1688 $commands.=' -swirl '.t3lib_div::intInRange($value,0,1000);
1689 break;
1690 case 'wave':
1691 $params = t3lib_div::intExplode(',',$value);
1692 $commands.=' -wave '.t3lib_div::intInRange($params[0],0,99).'x'.t3lib_div::intInRange($params[1],0,99);
1693 break;
1694 case 'charcoal':
1695 $commands.=' -charcoal '.t3lib_div::intInRange($value,0,100);
1696 break;
1697 case 'gray':
1698 $commands.=' -colorspace GRAY';
1699 break;
1700 case 'edge':
1701 $commands.=' -edge '.t3lib_div::intInRange($value,0,99);
1702 break;
1703 case 'emboss':
1704 $commands.=' -emboss';
1705 break;
1706 case 'flip':
1707 $commands.=' -flip';
1708 break;
1709 case 'flop':
1710 $commands.=' -flop';
1711 break;
1712 case 'colors':
1713 $commands.=' -colors '.t3lib_div::intInRange($value,2,255);
1714 break;
1715 case 'shear':
1716 $commands.=' -shear '.t3lib_div::intInRange($value,-90,90);
1717 break;
1718 case 'invert':
1719 $commands.=' -negate';
1720 break;
1721 }
1722 }
1723 return $commands;
1724 }
1725
1726 /**
1727 * Implements the "ADJUST" GIFBUILDER object
1728 *
1729 * @param pointer GDlib image pointer
1730 * @param array TypoScript array with configuration for the GIFBUILDER object.
1731 * @return void
1732 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1733 */
1734 function adjust(&$im, $conf) {
1735 $setup = $conf['value'];
1736 if (!trim($setup)){return '';}
1737 $effects = explode('|', $setup);
1738 foreach ($effects as $val) {
1739 $pairs=explode('=',$val,2);
1740 $value = trim($pairs[1]);
1741 $effect = strtolower(trim($pairs[0]));
1742 switch($effect) {
1743 case 'inputlevels': // low,high
1744 $params = t3lib_div::intExplode(',',$value);
1745 $this->inputLevels($im,$params[0],$params[1]);
1746 break;
1747 case 'outputlevels':
1748 $params = t3lib_div::intExplode(',',$value);
1749 $this->outputLevels($im,$params[0],$params[1]);
1750 break;
1751 case 'autolevels':
1752 $this->autoLevels($im);
1753 break;
1754 }
1755 }
1756 }
1757
1758 /**
1759 * Implements the "CROP" 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()
1765 */
1766 function crop(&$im,$conf) {
1767 $this->setWorkArea(''); // clears workArea to total image
1768 $cords = t3lib_div::intExplode(',',$conf['crop'].',,,');
1769 $conf['offset']=$cords[0].','.$cords[1];
1770 $cords = $this->objPosition($conf,$this->workArea,Array($cords[2],$cords[3]));
1771
1772 $newIm = $this->imagecreate($cords[2],$cords[3]);
1773 $cols=$this->convertColor($conf['backColor']?$conf['backColor']:$this->setup['backColor']);
1774 $Bcolor = ImageColorAllocate($newIm, $cols[0],$cols[1],$cols[2]);
1775 ImageFilledRectangle($newIm, 0, 0, $cords[2], $cords[3], $Bcolor);
1776
1777 $newConf = Array();
1778 $workArea = Array(0,0,$cords[2],$cords[3]);
1779 if ($cords[0]<0) {$workArea[0]=abs($cords[0]);} else {$newConf['offset']=-$cords[0];}
1780 if ($cords[1]<0) {$workArea[1]=abs($cords[1]);} else {$newConf['offset'].=','.-$cords[1];}
1781
1782 $this->copyGifOntoGif($newIm,$im,$newConf,$workArea);
1783 $im = $newIm;
1784 $this->w = imagesx($im);
1785 $this->h = imagesy($im);
1786 $this->setWorkArea(''); // clears workArea to total image
1787 }
1788
1789 /**
1790 * Implements the "SCALE" GIFBUILDER object
1791 *
1792 * @param pointer GDlib image pointer
1793 * @param array TypoScript array with configuration for the GIFBUILDER object.
1794 * @return void
1795 * @see tslib_gifBuilder::make()
1796 */
1797 function scale(&$im,$conf) {
1798 if ($conf['width'] || $conf['height'] || $conf['params']) {
1799 $tmpStr = $this->randomName();
1800 $theFile = $tmpStr.'.'.$this->gifExtension;
1801 $this->ImageWrite($im, $theFile);
1802 $theNewFile = $this->imageMagickConvert($theFile,$this->gifExtension,$conf['width'],$conf['height'],$conf['params'],'','');
1803 $tmpImg = $this->imageCreateFromFile($theNewFile[3]);
1804 if ($tmpImg) {
1805 ImageDestroy($im);
1806 $im = $tmpImg;
1807 $this->w = imagesx($im);
1808 $this->h = imagesy($im);
1809 $this->setWorkArea(''); // clears workArea to total image
1810 }
1811 if (!$this->dontUnlinkTempFiles) {
1812 unlink($theFile);
1813 if ($theNewFile[3] && $theNewFile[3]!=$theFile) {
1814 unlink($theNewFile[3]);
1815 }
1816 }
1817 }
1818 }
1819
1820 /**
1821 * Implements the "WORKAREA" GIFBUILDER object when setting it
1822 * Setting internal working area boundaries (->workArea)
1823 *
1824 * @param string Working area dimensions, comma separated
1825 * @return void
1826 * @access private
1827 * @see tslib_gifBuilder::make()
1828 */
1829 function setWorkArea($workArea) {
1830 $this->workArea = t3lib_div::intExplode(',',$workArea);
1831 $this->workArea = $this->applyOffset($this->workArea,$this->OFFSET);
1832 if (!$this->workArea[2]) {$this->workArea[2]=$this->w;}
1833 if (!$this->workArea[3]) {$this->workArea[3]=$this->h;}
1834 }
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858 /*************************
1859 *
1860 * Adjustment functions
1861 *
1862 ************************/
1863
1864 /**
1865 * Apply auto-levels to input image pointer
1866 *
1867 * @param integer GDlib Image Pointer
1868 * @return void
1869 */
1870 function autolevels(&$im) {
1871 $totalCols = ImageColorsTotal($im);
1872 $min=255;
1873 $max=0;
1874 for ($c=0; $c<$totalCols; $c++) {
1875 $cols = ImageColorsForIndex($im,$c);
1876 $grayArr[] = round(($cols['red']+$cols['green']+$cols['blue'])/3);
1877 }
1878 $min=min($grayArr);
1879 $max=max($grayArr);
1880 $delta = $max-$min;
1881 if ($delta) {
1882 for ($c=0; $c<$totalCols; $c++) {
1883 $cols = ImageColorsForIndex($im,$c);
1884 $cols['red'] = floor(($cols['red']-$min)/$delta*255);
1885 $cols['green'] = floor(($cols['green']-$min)/$delta*255);
1886 $cols['blue'] = floor(($cols['blue']-$min)/$delta*255);
1887 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1888 }
1889 }
1890 }
1891
1892 /**
1893 * Apply output levels to input image pointer (decreasing contrast)
1894 *
1895 * @param integer GDlib Image Pointer
1896 * @param integer The "low" value (close to 0)
1897 * @param integer The "high" value (close to 255)
1898 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1899 * @return void
1900 */
1901 function outputLevels(&$im,$low,$high,$swap='') {
1902 if ($low<$high){
1903 $low = t3lib_div::intInRange($low,0,255);
1904 $high = t3lib_div::intInRange($high,0,255);
1905
1906 if ($swap) {
1907 $temp = $low;
1908 $low = 255-$high;
1909 $high = 255-$temp;
1910 }
1911
1912 $delta = $high-$low;
1913 $totalCols = ImageColorsTotal($im);
1914 for ($c=0; $c<$totalCols; $c++) {
1915 $cols = ImageColorsForIndex($im,$c);
1916 $cols['red'] = $low+floor($cols['red']/255*$delta);
1917 $cols['green'] = $low+floor($cols['green']/255*$delta);
1918 $cols['blue'] = $low+floor($cols['blue']/255*$delta);
1919 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1920 }
1921 }
1922 }
1923
1924 /**
1925 * Apply input levels to input image pointer (increasing 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 inputLevels(&$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'] = t3lib_div::intInRange(($cols['red']-$low)/$delta*255, 0,255);
1949 $cols['green'] = t3lib_div::intInRange(($cols['green']-$low)/$delta*255, 0,255);
1950 $cols['blue'] = t3lib_div::intInRange(($cols['blue']-$low)/$delta*255, 0,255);
1951 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1952 }
1953 }
1954 }
1955
1956 /**
1957 * Reduce colors in image dependend on the actual amount of colors (Only works if we are not in truecolor mode)
1958 *
1959 * @param integer GDlib Image Pointer
1960 * @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.
1961 * @param integer Number of colors to reduce the image to.
1962 * @return void
1963 */
1964 function reduceColors(&$im,$limit, $cols) {
1965 if (!$this->truecolor && ImageColorsTotal($im)>=$limit) {
1966 $this->makeEffect($im, Array('value'=>'colors='.$cols) );
1967 }
1968 }
1969
1970 /**
1971 * Reduce colors in image using IM and create a palette based image if possible (<=256 colors)
1972 *
1973 * @param string Image file to reduce
1974 * @param integer Number of colors to reduce the image to.
1975 * @return string Reduced file
1976 */
1977 function IMreduceColors($file, $cols) {
1978 $fI = t3lib_div::split_fileref($file);
1979 $ext = strtolower($fI['fileext']);
1980 $result = $this->randomName().'.'.$ext;
1981 if (($reduce = t3lib_div::intInRange($cols, 0, ($ext=='gif'?256:$this->truecolorColors), 0))>0) {
1982 $params = ' -colors '.$reduce;
1983 if (!$this->im_version_4) {
1984 // IM4 doesn't have this options but forces them automatically if applicaple (<256 colors in image)
1985 if ($reduce<=256) { $params .= ' -type Palette'; }
1986 if ($ext=='png' && $reduce<=256) { $prefix = 'png8:'; }
1987 }
1988 $this->imageMagickExec($file, $prefix.$result, $params);
1989 if ($result) {
1990 return $result;
1991 }
1992 }
1993 return '';
1994 }
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006 /*********************************
2007 *
2008 * GIFBUILDER Helper functions
2009 *
2010 *********************************/
2011
2012 /**
2013 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
2014 * Use PATH_site unless we are in the backend.
2015 * Call it by t3lib_stdGraphic::prependAbsolutePath()
2016 *
2017 * @param string The font file
2018 * @return string The font file with absolute path.
2019 */
2020 function prependAbsolutePath($fontFile) {
2021 $absPath = defined('PATH_typo3') ? dirname(PATH_thisScript).'/' :PATH_site;
2022 $fontFile = t3lib_div::isAbsPath($fontFile) ? $fontFile : t3lib_div::resolveBackPath($absPath.$fontFile);
2023 return $fontFile;
2024 }
2025
2026 /**
2027 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
2028 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
2029 *
2030 * @param integer The sharpening factor, 0-100 (effectively in 10 steps)
2031 * @return string The sharpening command, eg. " -sharpen 3x4"
2032 * @see makeText(), IMparams(), v5_blur()
2033 */
2034 function v5_sharpen($factor) {
2035 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
2036
2037 $sharpenArr=explode(',',','.$this->im5fx_sharpenSteps);
2038 $sharpenF= trim($sharpenArr[$factor]);
2039 if ($sharpenF) {
2040 $cmd = ' -sharpen '.$sharpenF;
2041 return $cmd;
2042 }
2043 }
2044
2045 /**
2046 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
2047 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
2048 *
2049 * @param integer The blurring factor, 0-100 (effectively in 10 steps)
2050 * @return string The blurring command, eg. " -blur 3x4"
2051 * @see makeText(), IMparams(), v5_sharpen()
2052 */
2053 function v5_blur($factor) {
2054 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
2055
2056 $blurArr=explode(',',','.$this->im5fx_blurSteps);
2057 $blurF= trim($blurArr[$factor]);
2058 if ($blurF) {
2059 $cmd=' -blur '.$blurF;
2060 return $cmd;
2061 }
2062 }
2063
2064 /**
2065 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
2066 * 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.
2067 *
2068 * @return string
2069 */
2070 function randomName() {
2071 $this->createTempSubDir('temp/');
2072 return $this->tempPath.'temp/'.md5(uniqid(''));
2073 }
2074
2075 /**
2076 * Applies offset value to coordinated in $cords.
2077 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
2078 *
2079 * @param array Integer coordinates in key 0/1
2080 * @param array Offset values in key 0/1
2081 * @return array Modified $cords array
2082 */
2083 function applyOffset($cords,$OFFSET) {
2084 $cords[0] = intval($cords[0])+intval($OFFSET[0]);
2085 $cords[1] = intval($cords[1])+intval($OFFSET[1]);
2086 return $cords;
2087 }
2088
2089 /**
2090 * Converts a "HTML-color" TypoScript datatype to RGB-values.
2091 * Default is 0,0,0
2092 *
2093 * @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
2094 * @return array RGB values in key 0/1/2 of the array
2095 */
2096 function convertColor($string) {
2097 $col=array();
2098 $cParts = explode(':',$string,2);
2099
2100 // Finding the RGB definitions of the color:
2101 $string=$cParts[0];
2102 if (strstr($string,'#')) {
2103 $string = preg_replace('/[^A-Fa-f0-9]*/','',$string);
2104 $col[]=HexDec(substr($string,0,2));
2105 $col[]=HexDec(substr($string,2,2));
2106 $col[]=HexDec(substr($string,4,2));
2107 } elseif (strstr($string,',')) {
2108 $string = preg_replace('/[^,0-9]*/','',$string);
2109 $strArr = explode(',',$string);
2110 $col[]=intval($strArr[0]);
2111 $col[]=intval($strArr[1]);
2112 $col[]=intval($strArr[2]);
2113 } else {
2114 $string = strtolower(trim($string));
2115 if ($this->colMap[$string]) {
2116 $col = $this->colMap[$string];
2117 } else {
2118 $col = Array(0,0,0);
2119 }
2120 }
2121 // ... and possibly recalculating the value
2122 if (trim($cParts[1])) {
2123 $cParts[1]=trim($cParts[1]);
2124 if (substr($cParts[1],0,1)=='*') {
2125 $val=doubleval(substr($cParts[1],1));
2126 $col[0]=t3lib_div::intInRange($col[0]*$val,0,255);
2127 $col[1]=t3lib_div::intInRange($col[1]*$val,0,255);
2128 $col[2]=t3lib_div::intInRange($col[2]*$val,0,255);
2129 } else {
2130 $val=intval($cParts[1]);
2131 $col[0]=t3lib_div::intInRange($col[0]+$val,0,255);
2132 $col[1]=t3lib_div::intInRange($col[1]+$val,0,255);
2133 $col[2]=t3lib_div::intInRange($col[2]+$val,0,255);
2134 }
2135 }
2136 return $col;
2137 }
2138
2139 /**
2140 * Recode string
2141 * Used with text strings for fonts when languages has other character sets.
2142 *
2143 * @param string The text to recode
2144 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
2145 */
2146 function recodeString($string) {
2147 // Recode string to UTF-8 from $this->nativeCharset:
2148 if ($this->nativeCharset && $this->nativeCharset!='utf-8') {
2149 $string = $this->csConvObj->utf8_encode($string,$this->nativeCharset); // Convert to UTF-8
2150 }
2151
2152 // Recode string accoding to TTFLocaleConv. Deprecated.
2153 if ($this->TTFLocaleConv) {
2154 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.');
2155
2156 list($from, $to) = t3lib_div::trimExplode('..', $this->TTFLocaleConv, true);
2157 $string = $this->csConvObj->conv($string, $from, $to);
2158 }
2159
2160 return $string;
2161 }
2162
2163 /**
2164 * Split a string into an array of individual characters
2165 * 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.
2166 *
2167 * @param string The text string to split
2168 * @param boolean Return Unicode numbers instead of chars.
2169 * @return array Numerical array with a char as each value.
2170 */
2171 function singleChars($theText,$returnUnicodeNumber=FALSE) {
2172 if ($this->nativeCharset) {
2173 return $this->csConvObj->utf8_to_numberarray($theText,1,$returnUnicodeNumber ? 0 : 1); // Get an array of separated UTF-8 chars
2174 } else {
2175 $output=array();
2176 $c=strlen($theText);
2177 for($a=0;$a<$c;$a++) {
2178 $output[]=substr($theText,$a,1);
2179 }
2180 return $output;
2181 }
2182 }
2183
2184 /**
2185 * 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
2186 *
2187 * @param array TypoScript configuration for a GIFBUILDER object
2188 * @param array Workarea definition
2189 * @param array BB (Bounding box) array. Not just used for TEXT objects but also for others
2190 * @return array [0]=x, [1]=y, [2]=w, [3]=h
2191 * @access private
2192 * @see copyGifOntoGif(), makeBox(), crop()
2193 */
2194 function objPosition($conf,$workArea,$BB) {
2195 // offset, align, valign, workarea
2196 $result=Array();
2197 $result[2] = $BB[0];
2198 $result[3] = $BB[1];
2199 $w=$workArea[2];
2200 $h=$workArea[3];
2201
2202 $align = explode(',',$conf['align']);
2203 $align[0] = strtolower(substr(trim($align[0]),0,1));
2204 $align[1] = strtolower(substr(trim($align[1]),0,1));
2205
2206 switch($align[0]) {
2207 case 'r':
2208 $result[0]=$w-$result[2];
2209 break;
2210 case 'c':
2211 $result[0] = round(($w-$result[2])/2);
2212 break;
2213 default:
2214 $result[0] = 0;
2215 break;
2216 }
2217 switch($align[1]) {
2218 case 'b':
2219 $result[1] = $h-$result[3]; // y pos
2220 break;
2221 case 'c':
2222 $result[1] = round(($h-$result[3])/2);
2223 break;
2224 default:
2225 $result[1]=0;
2226 break;
2227 }
2228 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
2229 $result = $this->applyOffset($result,$workArea);
2230 return $result;
2231 }
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253 /***********************************
2254 *
2255 * Scaling, Dimensions of images
2256 *
2257 ***********************************/
2258
2259 /**
2260 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
2261 *
2262 * @param string The image filepath
2263 * @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.
2264 * @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
2265 * @param string Height. See $w
2266 * @param string Additional ImageMagick parameters.
2267 * @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...
2268 * @param array An array with options passed to getImageScale (see this function).
2269 * @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.
2270 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
2271 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
2272 */
2273 function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0) {
2274 if ($this->NO_IMAGE_MAGICK) {
2275 // Returning file info right away
2276 return $this->getImageDimensions($imagefile);
2277 }
2278
2279 if($info=$this->getImageDimensions($imagefile)) {
2280 $newExt=strtolower(trim($newExt));
2281 if (!$newExt) { // If no extension is given the original extension is used
2282 $newExt = $info[2];
2283 }
2284 if ($newExt=='web') {
2285 if (t3lib_div::inList($this->webImageExt,$info[2])) {
2286 $newExt = $info[2];
2287 } else {
2288 $newExt = $this->gif_or_jpg($info[2],$info[0],$info[1]);
2289 if (!$params) {
2290 $params = $this->cmds[$newExt];
2291 }
2292 }
2293 }
2294 if (t3lib_div::inList($this->imageFileExt,$newExt)) {
2295 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
2296
2297 $data = $this->getImageScale($info,$w,$h,$options);
2298 $w=$data['origW'];
2299 $h=$data['origH'];
2300
2301 // if no convertion should be performed
2302 $wh_noscale = (!$w && !$h) || ($data[0]==$info[0] && $data[1]==$info[1]); // this flag is true if the width / height does NOT dictate the image to be scaled!! (that is if no w/h is given or if the destination w/h matches the original image-dimensions....
2303
2304 if ($wh_noscale && !$data['crs'] && !$params && !$frame && $newExt==$info[2] && !$mustCreate) {
2305 $info[3] = $imagefile;
2306 return $info;
2307 }
2308 $info[0]=$data[0];
2309 $info[1]=$data[1];
2310
2311 $frame = $this->noFramePrepended ? '' : intval($frame);
2312
2313 if (!$params) {
2314 $params = $this->cmds[$newExt];
2315 }
2316
2317 // Cropscaling:
2318 if ($data['crs']) {
2319 if (!$data['origW']) { $data['origW'] = $data[0]; }
2320 if (!$data['origH']) { $data['origH'] = $data[1]; }
2321 $offsetX = intval(($data[0] - $data['origW']) * ($data['cropH']+100)/200);
2322 $offsetY = intval(($data[1] - $data['origH']) * ($data['cropV']+100)/200);
2323 $params .= ' -crop '.$data['origW'].'x'.$data['origH'].'+'.$offsetX.'+'.$offsetY.' ';
2324 }
2325
2326 $command = $this->scalecmd.' '.$info[0].'x'.$info[1].'! '.$params.' ';
2327 $cropscale = ($data['crs'] ? 'crs-V'.$data['cropV'].'H'.$data['cropH'] : '');
2328
2329 if ($this->alternativeOutputKey) {
2330 $theOutputName = t3lib_div::shortMD5($command.$cropscale.basename($imagefile).$this->alternativeOutputKey.'['.$frame.']');
2331 } else {
2332 $theOutputName = t3lib_div::shortMD5($command.$cropscale.$imagefile.filemtime($imagefile).'['.$frame.']');
2333 }
2334 if ($this->imageMagickConvert_forceFileNameBody) {
2335 $theOutputName = $this->imageMagickConvert_forceFileNameBody;
2336 $this->imageMagickConvert_forceFileNameBody='';
2337 }
2338
2339 // Making the temporary filename:
2340 $this->createTempSubDir('pics/');
2341 $output = $this->absPrefix.$this->tempPath.'pics/'.$this->filenamePrefix.$theOutputName.'.'.$newExt;
2342
2343 // Register temporary filename:
2344 $GLOBALS['TEMP_IMAGES_ON_PAGE'][] = $output;
2345
2346 if ($this->dontCheckForExistingTempFile || !$this->file_exists_typo3temp_file($output, $imagefile)) {
2347 $this->imageMagickExec($imagefile, $output, $command, $frame);
2348 }
2349 if (file_exists($output)) {
2350 $info[3] = $output;
2351 $info[2] = $newExt;
2352 if ($params) { // params could realisticly change some imagedata!
2353 $info=$this->getImageDimensions($info[3]);
2354 }
2355 if ($info[2]==$this->gifExtension && !$this->dontCompress) {
2356 t3lib_div::gif_compress($info[3],''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2357 }
2358 return $info;
2359 }
2360 }
2361 }
2362 }
2363
2364 /**
2365 * Gets the input image dimensions.
2366 *
2367 * @param string The image filepath
2368 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2369 * @see imageMagickConvert(), tslib_cObj::getImgResource()
2370 */
2371 function getImageDimensions($imageFile) {
2372 preg_match('/([^\.]*)$/',$imageFile,$reg);
2373 if (file_exists($imageFile) && t3lib_div::inList($this->imageFileExt,strtolower($reg[0]))) {
2374 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
2375 return $returnArr;
2376 } else {
2377 if ($temp = @getImageSize($imageFile)) {
2378 $returnArr = Array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
2379 } else {
2380 $returnArr = $this->imageMagickIdentify($imageFile);
2381 }
2382 if ($returnArr) {
2383 $this->cacheImageDimensions($returnArr);
2384 return $returnArr;
2385 }
2386 }
2387 }
2388 return false;
2389 }
2390
2391 /**
2392 * Cache the result of the getImageDimensions function into the database. Does not check if the
2393 * file exists!
2394 *
2395 * @param array $identifyResult: Result of the getImageDimensions function
2396 * @return boolean True if operation was successful
2397 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2398 */
2399 function cacheImageDimensions($identifyResult) {
2400 global $TYPO3_DB;
2401 // Create a md5 hash of the filename
2402 $md5Hash = md5_file($identifyResult[3]);
2403 if ($md5Hash) {
2404 $fieldArr = array (
2405 'md5hash' => $md5Hash,
2406 'md5filename' => md5($identifyResult[3]),
2407 'tstamp' => $GLOBALS['EXEC_TIME'],
2408 'filename' => $identifyResult[3],
2409 'imagewidth' => $identifyResult[0],
2410 'imageheight' => $identifyResult[1],
2411 );
2412 $TYPO3_DB->exec_INSERTquery('cache_imagesizes', $fieldArr);
2413 if (!$err = $TYPO3_DB->sql_error()) {
2414 return true;
2415 }
2416 }
2417 return false;
2418 }
2419
2420 /**
2421 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
2422 *
2423 * @param string The image filepath
2424 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2425 * @author Michael Stucki <michael@typo3.org> / Robert Lemke <rl@robertlemke.de>
2426 */
2427 function getCachedImageDimensions($imageFile) {
2428 global $TYPO3_DB;
2429 // Create a md5 hash of the filename
2430 $md5Hash = md5_file($imageFile);
2431 preg_match('/([^\.]*)$/',$imageFile,$reg);
2432 $res = $TYPO3_DB->exec_SELECTquery ('md5hash, imagewidth, imageheight', 'cache_imagesizes', 'md5filename='.$TYPO3_DB->fullQuoteStr(md5($imageFile),'cache_imagesizes'));
2433 if ($res) {
2434 if ($row = $TYPO3_DB->sql_fetch_assoc($res)) {
2435 if ($row['md5hash']!=$md5Hash) {
2436 // file has changed, delete the row
2437 $TYPO3_DB->exec_DELETEquery ('cache_imagesizes', 'md5hash='.$TYPO3_DB->fullQuoteStr($row['md5hash'],'cache_imagesizes'));
2438 } else {
2439 return (array((int) $row['imagewidth'], (int) $row['imageheight'], strtolower($reg[0]), $imageFile));
2440 }
2441 }
2442 }
2443 return false;
2444 }
2445
2446 /**
2447 * Get numbers for scaling the image based on input
2448 *
2449 * @param array Current image information: Width, Height etc.
2450 * @param integer "required" width
2451 * @param integer "required" height
2452 * @param array Options: Keys are like "maxW", "maxH", "minW", "minH"
2453 * @return array
2454 * @access private
2455 * @see imageMagickConvert()
2456 */
2457 function getImageScale($info,$w,$h,$options) {
2458 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
2459
2460 if (strstr($w.$h, 'c')) {
2461 $out['cropH'] = intval(substr(strstr($w, 'c'), 1));
2462 $out['cropV'] = intval(substr(strstr($h, 'c'), 1));
2463 $crs = true;
2464 } else {
2465 $crs = false;
2466 }
2467 $out['crs'] = $crs;
2468
2469 $w=intval($w);
2470 $h=intval($h);
2471 // if there are max-values...
2472 if ($options['maxW']) {
2473 if ($w) { // if width is given...
2474 if ($w>$options['maxW']) {
2475 $w=$options['maxW'];
2476 $max=1; // height should follow
2477 }
2478 } else {
2479 if ($info[0]>$options['maxW']) {
2480 $w=$options['maxW'];
2481 $max=1; // height should follow
2482 }
2483 }
2484 }
2485 if ($options['maxH']) {
2486 if ($h) { // if height is given...
2487 if ($h>$options['maxH']) {
2488 $h=$options['maxH'];
2489 $max=1; // height should follow
2490 }
2491 } else {
2492 if ($info[1]>$options['maxH']) { // Changed [0] to [1] 290801
2493 $h=$options['maxH'];
2494 $max=1; // height should follow
2495 }
2496 }
2497 }
2498 $out['origW']=$w;
2499 $out['origH']=$h;
2500 $out['max'] = $max;
2501
2502 if (!$this->mayScaleUp) {
2503 if ($w>$info[0]){$w=$info[0];}
2504 if ($h>$info[1]){$h=$info[1];}
2505 }
2506 if ($w || $h) { // if scaling should be performed
2507 if ($w && !$h) {
2508 $info[1] = ceil($info[1]*($w/$info[0]));
2509 $info[0] = $w;
2510 }
2511 if (!$w && $h) {
2512 $info[0] = ceil($info[0]*($h/$info[1]));
2513 $info[1] = $h;
2514 }
2515 if ($w && $h) {
2516 if ($max) {
2517 $ratio = $info[0]/$info[1];
2518 if ($h*$ratio > $w) {
2519 $h = round($w/$ratio);
2520 } else {
2521 $w = round($h*$ratio);
2522 }
2523 }
2524 if ($crs) {
2525 $ratio = $info[0] / $info[1];
2526 if ($h * $ratio < $w) {
2527 $h = round($w / $ratio);
2528 } else {
2529 $w = round($h * $ratio);
2530 }
2531 }
2532 $info[0] = $w;
2533 $info[1] = $h;
2534 }
2535 }
2536 $out[0]=$info[0];
2537 $out[1]=$info[1];
2538 // Set minimum-measures!
2539 if ($options['minW'] && $out[0]<$options['minW']) {
2540 if (($max || $crs) && $out[0]) {
2541 $out[1]= round($out[1]*$options['minW']/$out[0]);
2542 }
2543 $out[0]=$options['minW'];
2544 }
2545 if ($options['minH'] && $out[1]<$options['minH']) {
2546 if (($max || $crs) && $out[1]) {
2547 $out[0]= round($out[0]*$options['minH']/$out[1]);
2548 }
2549 $out[1]=$options['minH'];
2550 }
2551
2552 return $out;
2553 }
2554
2555 /**
2556 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2557 *
2558 * @param string Output imagefile
2559 * @param string Original basis file
2560 * @return boolean Returns true if the file is already being made; thus "true" means "Don't render the image again"
2561 * @access private
2562 */
2563 function file_exists_typo3temp_file($output,$orig='') {
2564 if ($this->enable_typo3temp_db_tracking) {
2565 if (file_exists($output)) { // If file exists, then we return immediately
2566 return 1;
2567 } else { // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2568 $md5Hash=md5($output);
2569 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2570 'md5hash',
2571 'cache_typo3temp_log',
2572 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log') . ' AND tstamp>' . ($GLOBALS['EXEC_TIME'] - 30)
2573 );
2574 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // If there was a record, the image is being generated by another proces (we assume)
2575 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...)
2576 if (is_object($GLOBALS['TT'])) $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: '.$output);
2577 return 2; // Return 'success - 2'
2578 } 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.
2579
2580 $insertFields = array(
2581 'md5hash' => $md5Hash,
2582 'tstamp' => $GLOBALS['EXEC_TIME'],
2583 'filename' => $output,
2584 'orig_filename' => $orig
2585 );
2586 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5Hash, 'cache_typo3temp_log'));
2587 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2588
2589 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);
2590 return 0;
2591 }
2592 }
2593 } else {
2594 return file_exists($output);
2595 }
2596 }
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615 /***********************************
2616 *
2617 * ImageMagick API functions
2618 *
2619 ***********************************/
2620
2621 /**
2622 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2623 * Using ImageMagick
2624 *
2625 * @param string The relative (to PATH_site) image filepath
2626 * @return array
2627 */
2628 function imageMagickIdentify($imagefile) {
2629 if (!$this->NO_IMAGE_MAGICK) {
2630 $frame = $this->noFramePrepended?'':'[0]';
2631 $cmd = t3lib_div::imageMagickCommand('identify', $this->wrapFileName($imagefile).$frame);
2632 $returnVal = array();
2633 exec($cmd, $returnVal);
2634 $splitstring=$returnVal[0];
2635 $this->IM_commands[] = Array ('identify',$cmd,$returnVal[0]);
2636 if ($splitstring) {
2637 preg_match('/([^\.]*)$/',$imagefile,$reg);
2638 $splitinfo = explode(' ', $splitstring);
2639 foreach ($splitinfo as $key => $val) {
2640 $temp = '';
2641 if ($val) {$temp = explode('x', $val);}
2642 if (intval($temp[0]) && intval($temp[1])) {
2643 $dim=$temp;
2644 break;
2645 }
2646 }
2647 if ($dim[0] && $dim[1]) {
2648 return Array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2649 }
2650 }
2651 }
2652 }
2653
2654 /**
2655 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2656 * Can be used for many things, mostly scaling and effects.
2657 *
2658 * @param string The relative (to PATH_site) image filepath, input file (read from)
2659 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2660 * @param string ImageMagick parameters
2661 * @param integer Optional, refers to which frame-number to select in the image. '' or 0
2662 * will select the first frame, 1 will select the next and so on...
2663 * @return string The result of a call to PHP function "exec()"
2664 */
2665 function imageMagickExec($input, $output, $params, $frame = 0) {
2666 if (!$this->NO_IMAGE_MAGICK) {
2667
2668 // Unless noFramePrepended is set in the Install Tool, a frame number is added to
2669 // select a specific page of the image (by default this will be the first page)
2670 if (!$this->noFramePrepended) {
2671 $frame = '[' . intval($frame) . ']';
2672 } else {
2673 $frame = '';
2674 }
2675
2676 $cmd = t3lib_div::imageMagickCommand('convert', $params . ' ' . $this->wrapFileName($input) . $frame . ' ' . $this->wrapFileName($output));
2677 $this->IM_commands[] = array($output,$cmd);
2678
2679 $ret = exec($cmd);
2680 t3lib_div::fixPermissions($output); // Change the permissions of the file
2681
2682 return $ret;
2683 }
2684 }
2685
2686 /**
2687 * 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)
2688 * Can be used for many things, mostly scaling and effects.
2689 *
2690 * @param string The relative (to PATH_site) image filepath, bottom file
2691 * @param string The relative (to PATH_site) image filepath, overlay file (top)
2692 * @param string The relative (to PATH_site) image filepath, the mask file (grayscale)
2693 * @param string The relative (to PATH_site) image filepath, output filename (written to)
2694 * @param [type] $handleNegation: ...
2695 * @return void
2696 */
2697 function combineExec($input,$overlay,$mask,$output, $handleNegation = false) {
2698 if (!$this->NO_IMAGE_MAGICK) {
2699 $params = '-colorspace GRAY +matte';
2700 if ($handleNegation) {
2701 if ($this->maskNegate) {
2702 $params .= ' '.$this->maskNegate;
2703 }
2704 }
2705 $theMask = $this->randomName().'.'.$this->gifExtension;
2706 $this->imageMagickExec($mask, $theMask, $params);
2707 $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
2708 $this->IM_commands[] = Array ($output,$cmd);
2709
2710 $ret = exec($cmd);
2711 t3lib_div::fixPermissions($output); // Change the permissions of the file
2712
2713 if (is_file($theMask)) {
2714 @unlink($theMask);
2715 }
2716
2717 return $ret;
2718 }
2719 }
2720
2721 /**
2722 * Escapes a file name so it can safely be used on the command line.
2723 *
2724 * @param string $inputName filename to safeguard, must not be empty
2725 *
2726 * @return string $inputName escaped as needed
2727 */
2728 protected function wrapFileName($inputName) {
2729 return escapeshellarg($inputName);
2730 }
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754 /***********************************
2755 *
2756 * Various IO functions
2757 *
2758 ***********************************/
2759
2760 /**
2761 * Returns true if the input file existed
2762 *
2763 * @param string Input file to check
2764 * @return string Returns the filename if the file existed, otherwise empty.
2765 */
2766 function checkFile($file) {
2767 if (@is_file($file)) {
2768 return $file;
2769 } else {
2770 return '';
2771 }
2772 }
2773
2774 /**
2775 * Creates subdirectory in typo3temp/ if not already found.
2776 *
2777 * @param string Name of sub directory
2778 * @return boolean Result of t3lib_div::mkdir(), true if it went well.
2779 */
2780 function createTempSubDir($dirName) {
2781
2782 // Checking if the this->tempPath is already prefixed with PATH_site and if not, prefix it with that constant.
2783 if (t3lib_div::isFirstPartOfStr($this->tempPath,PATH_site)) {
2784 $tmpPath = $this->tempPath;
2785 } else {
2786 $tmpPath = PATH_site.$this->tempPath;
2787 }
2788
2789 // Making the temporary filename:
2790 if (!@is_dir($tmpPath.$dirName)) {
2791 return t3lib_div::mkdir($tmpPath.$dirName);
2792 }
2793 }
2794
2795 /**
2796 * 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.
2797 *
2798 * @param pointer The image pointer (reference)
2799 * @param string The ImageMagick parameters. Like effects, scaling etc.
2800 * @return void
2801 */
2802 function applyImageMagickToPHPGif(&$im, $command) {
2803 $tmpStr = $this->randomName();
2804 $theFile = $tmpStr.'.'.$this->gifExtension;
2805 $this->ImageWrite($im, $theFile);
2806 $this->imageMagickExec($theFile,$theFile,$command);
2807 $tmpImg = $this->imageCreateFromFile($theFile);
2808 if ($tmpImg) {
2809 ImageDestroy($im);
2810 $im = $tmpImg;
2811 $this->w = imagesx($im);
2812 $this->h = imagesy($im);
2813 }
2814 if (!$this->dontUnlinkTempFiles) {
2815 unlink($theFile);
2816 }
2817 }
2818
2819 /**
2820 * 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.
2821 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2822 *
2823 * @param string The file extension, lowercase.
2824 * @param integer The width of the output image.
2825 * @param integer The height of the output image.
2826 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2827 */
2828 function gif_or_jpg($type,$w,$h) {
2829 if ($type=='ai' || $w*$h < $this->pixelLimitGif) {
2830 return $this->gifExtension;
2831 } else {
2832 return 'jpg';
2833 }
2834 }
2835
2836 /**
2837 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2838 * Used in GIFBUILDER
2839 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
2840 *
2841 * @param string The filename to write to.
2842 * @return string Returns input filename
2843 * @see tslib_gifBuilder::gifBuild()
2844 */
2845 function output($file) {
2846 if ($file) {
2847 $reg = array();
2848 preg_match('/([^\.]*)$/',$file,$reg);
2849 $ext=strtolower($reg[0]);
2850 switch($ext) {
2851 case 'gif':
2852 case 'png':
2853 if ($this->ImageWrite($this->im, $file)) {
2854 // ImageMagick operations
2855 if ($this->setup['reduceColors'] || (!$this->png_truecolor && $this->truecolor)) {
2856 $reduced = $this->IMreduceColors($file, t3lib_div::intInRange($this->setup['reduceColors'], 256, $this->truecolorColors, 256));
2857 if ($reduced) {
2858 @copy($reduced, $file);
2859 @unlink($reduced);
2860 }
2861 }
2862 t3lib_div::gif_compress($file, 'IM'); // Compress with IM! (adds extra compression, LZW from ImageMagick) (Workaround for the absence of lzw-compression in GD)
2863 }
2864 break;
2865 case 'jpg':
2866 case 'jpeg':
2867 $quality = 0; // Use the default
2868 if($this->setup['quality']) {
2869 $quality = t3lib_div::intInRange($this->setup['quality'],10,100);
2870 }
2871 if ($this->ImageWrite($this->im, $file, $quality));
2872 break;
2873 }
2874 $GLOBALS['TEMP_IMAGES_ON_PAGE'][]=$file;
2875 }
2876 return $file;
2877 }
2878
2879 /**
2880 * Destroy internal image pointer, $this->im
2881 *
2882 * @return void
2883 * @see tslib_gifBuilder::gifBuild()
2884 */
2885 function destroy() {
2886 ImageDestroy($this->im);
2887 }
2888
2889 /**
2890 * Returns Image Tag for input image information array.
2891 *
2892 * @param array Image information array, key 0/1 is width/height and key 3 is the src value
2893 * @return string Image tag for the input image information array.
2894 */
2895 function imgTag ($imgInfo) {
2896 return '<img src="'.$imgInfo[3].'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'" border="0" alt="" />';
2897 }
2898
2899 /**
2900 * Writes the input GDlib image pointer to file
2901 *
2902 * @param pointer The GDlib image resource pointer
2903 * @param string The filename to write to
2904 * @param integer The image quality (for JPEGs)
2905 * @return boolean The output of either imageGif, imagePng or imageJpeg based on the filename to write
2906 * @see maskImageOntoImage(), scale(), output()
2907 */
2908 function ImageWrite($destImg, $theImage, $quality=0) {
2909 imageinterlace ($destImg,0);
2910 $ext = strtolower(substr($theImage, strrpos($theImage, '.')+1));
2911 $result = FALSE;
2912 switch ($ext) {
2913 case 'jpg':
2914 case 'jpeg':
2915 if (function_exists('imageJpeg')) {
2916 if ($quality == 0) {
2917 $quality = $this->jpegQuality;
2918 }
2919 $result = imageJpeg($destImg, $theImage, $quality);
2920 }
2921 break;
2922 case 'gif':
2923 if (function_exists('imageGif')) {
2924 if ($this->truecolor) {
2925 imagetruecolortopalette($destImg, true, 256);
2926 }
2927 $result = imageGif($destImg, $theImage);
2928 }
2929 break;
2930 case 'png':
2931 if (function_exists('imagePng')) {
2932 $result = ImagePng($destImg, $theImage);
2933 }
2934 break;
2935 }
2936 if ($result) {
2937 t3lib_div::fixPermissions($theImage);
2938 }
2939 return $result;
2940 }
2941
2942
2943
2944 /**
2945 * Writes the input GDlib image pointer to file. Now just a wrapper to ImageWrite.
2946 *
2947 * @param pointer The GDlib image resource pointer
2948 * @param string The filename to write to
2949 * @return mixed The output of either imageGif, imagePng