* Added "altText" and "titleText" attributes to the IMGMAP object (used for IMGMENU...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_stdgraphic.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2004 Kasper Skaarhoj (kasper@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 <kasper@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 143: class t3lib_stdGraphic
41 * 218: function init()
42 *
43 * SECTION: Layering images / "IMAGE" GIFBUILDER object
44 * 317: function maskImageOntoImage(&$im,$conf,$workArea)
45 * 377: function copyImageOntoImage(&$im,$conf,$workArea)
46 * 399: function copyGifOntoGif(&$im,$cpImg,$conf,$workArea)
47 * 478: function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h)
48 *
49 * SECTION: Text / "TEXT" GIFBUILDER object
50 * 527: function makeText(&$im,$conf,$workArea)
51 * 643: function txtPosition($conf,$workArea,$BB)
52 * 697: function calcBBox($conf)
53 * 766: function addToMap($cords,$conf)
54 * 787: function calcTextCordsForMap($cords,$offset, $conf)
55 * 820: function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing)
56 * 853: function fontResize($conf)
57 *
58 * SECTION: Other GIFBUILDER objects related to TEXT
59 * 915: function makeOutline(&$im,$conf,$workArea,$txtConf)
60 * 944: function circleOffset($distance, $iterations)
61 * 968: function makeEmboss(&$im,$conf,$workArea,$txtConf)
62 * 990: function makeShadow(&$im,$conf,$workArea,$txtConf)
63 *
64 * SECTION: Other GIFBUILDER objects
65 * 1120: function makeBox(&$im,$conf,$workArea)
66 * 1139: function makeEffect(&$im, $conf)
67 * 1154: function IMparams($setup)
68 * 1237: function adjust(&$im, $conf)
69 * 1269: function crop(&$im,$conf)
70 * 1299: function scale(&$im,$conf)
71 * 1331: function setWorkArea($workArea)
72 *
73 * SECTION: Adjustment functions
74 * 1372: function autolevels(&$im)
75 * 1403: function outputLevels(&$im,$low,$high,$swap='')
76 * 1435: function inputLevels(&$im,$low,$high,$swap='')
77 * 1466: function reduceColors(&$im,$limit, $cols)
78 *
79 * SECTION: GIFBUILDER Helper functions
80 * 1504: function prependAbsolutePath($fontFile)
81 * 1518: function v5_sharpen($factor)
82 * 1537: function v5_blur($factor)
83 * 1554: function randomName()
84 * 1566: function applyOffset($cords,$OFFSET)
85 * 1579: function convertColor($string)
86 * 1629: function recodeString($string)
87 * 1650: function singleChars($theText)
88 * 1673: function objPosition($conf,$workArea,$BB)
89 *
90 * SECTION: Scaling, Dimensions of images
91 * 1752: function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0)
92 * 1835: function getImageDimensions($imageFile)
93 * 1863: function cacheImageDimensions($identifyResult)
94 * 1895: function getCachedImageDimensions($imageFile)
95 * 1930: function getImageScale($info,$w,$h,$options)
96 * 2018: function file_exists_typo3temp_file($output,$orig='')
97 *
98 * SECTION: ImageMagick API functions
99 * 2079: function imageMagickIdentify($imagefile)
100 * 2112: function imageMagickExec($input,$output,$params)
101 * 2130: function combineExec($input,$overlay,$mask,$output)
102 * 2145: function wrapFileName($inputName)
103 *
104 * SECTION: Various IO functions
105 * 2186: function checkFile($file)
106 * 2201: function applyImageMagickToPHPGif(&$im, $command)
107 * 2227: function gif_or_jpg($type,$w,$h)
108 * 2244: function output($file)
109 * 2288: function destroy()
110 * 2298: function imgTag ($imgInfo)
111 * 2310: function ImageGif($destImg, $theImage)
112 * 2327: function imageCreateFromGif($sourceImg)
113 *
114 * TOTAL FUNCTIONS: 54
115 * (This index is automatically created/updated by the extension "extdeveval")
116 *
117 */
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 /**
135 * Class contains a bunch of cool functions for manipulating graphics with GDlib/Freetype and ImageMagick
136 * VERY OFTEN used with gifbuilder that extends this class and provides a TypoScript API to using these functions
137 *
138 * @author Kasper Skaarhoj <kasper@typo3.com>
139 * @package TYPO3
140 * @subpackage t3lib
141 * @see tslib_gifBuilder
142 */
143 class t3lib_stdGraphic {
144
145 // Internal configuration, set in init()
146 var $combineScript = 'combine'; // The ImageMagick filename used for combining two images. This name changed during the versions.
147 var $noFramePrepended=0; // If set, there is no frame pointer prepended to the filenames.
148 var $GD2=0; // Set, if the GDlib used is version 2.
149 var $gifExtension = 'gif'; // This should be changed to 'png' if you want this class to read/make PNG-files instead!
150 var $TTFLocaleConv = ''; // Used to recode input to TTF-functions for other charsets.
151 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.
152 var $imageMagickPath = ''; // path to imageMagick, eg: /usr/lib/
153 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!
154 var $webImageExt = 'gif,jpg,jpeg,png'; // Commalist of web image extensions (can be shown by a webbrowser)
155 var $maskNegate = ''; // Will be ' -negate' if ImageMagick ver 5.2+. See init();
156 var $NO_IM_EFFECTS = '';
157 var $cmds = Array (
158 'jpg' => '-colorspace RGB -sharpen 50 -quality 60',
159 'jpeg' => '-colorspace RGB -sharpen 50 -quality 60',
160 'gif' => '-colors 64',
161 'png' => '-colors 64'
162 );
163 var $NO_IMAGE_MAGICK = '';
164 var $V5_EFFECTS = 0;
165 var $mayScaleUp = 1;
166
167 // Variables for testing, alternative usage etc.
168 var $filenamePrefix=''; // Filename prefix for images scaled in imageMagickConvert()
169 var $imageMagickConvert_forceFileNameBody=''; // Forcing the output filename of imageMagickConvert() to this value. However after calling imageMagickConvert() it will be set blank again.
170 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.
171 var $dontCompress=0; // Prevents imageMagickConvert() from compressing the gif-files with t3lib_div::gif_compress()
172 var $dontUnlinkTempFiles=0; // For debugging ONLY!
173 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...
174
175 // Internal:
176 var $IM_commands = Array(); // All ImageMagick commands executed is stored in this array for tracking. Used by the Install Tools Image section
177 var $workArea = Array();
178
179 // Constants:
180 var $tempPath = 'typo3temp/'; // The temp-directory where to store the files. Relative to PATH_site.
181 var $scalecmd = '-geometry'; // ImageMagick scaling command; "-geometry" eller "-sample". Used in makeText() and imageMagickConvert()
182 var $im5fx_blurSteps='1x2,2x2,3x2,4x3,5x3,5x4,6x4,7x5,8x5,9x5'; // Used by v5_blur() to simulate 10 continuous steps of blurring
183 var $im5fx_sharpenSteps='1x2,2x2,3x2,2x3,3x3,4x3,3x4,4x4,4x5,5x5'; // Used by v5_sharpen() to simulate 10 continuous steps of sharpening.
184 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
185 var $colMap = Array ( // Array mapping HTML color names to RGB values.
186 'aqua' => Array(0,255,255),
187 'black' => Array(0,0,0),
188 'blue' => Array(0,0,255),
189 'fuchsia' => Array(255,0,255),
190 'gray' => Array(128,128,128),
191 'green' => Array(0,128,0),
192 'lime' => Array(0,255,0),
193 'maroon' => Array(128,0,0),
194 'navy' => Array(0,0,128),
195 'olive' => Array(128,128,0),
196 'purple' => Array(128,0,128),
197 'red' => Array(255,0,0),
198 'silver' => Array(192,192,192),
199 'teal' => Array(0,128,128),
200 'yellow' => Array(255,255,0),
201 'white' => Array(255,255,255)
202 );
203
204 // Charset conversion object:
205 var $csConvObj;
206 var $nativeCharset=''; // Is set to the native character set of the input strings.
207
208
209
210
211
212 /**
213 * Init function. Must always call this when using the class.
214 * This function will read the configuration information from $GLOBALS['TYPO3_CONF_VARS']['GFX'] can set some values in internal variables.
215 *
216 * @return void
217 */
218 function init() {
219 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
220
221 if ($gfxConf['im_combine_filename']) $this->combineScript=$gfxConf['im_combine_filename'];
222 if ($gfxConf['im_noFramePrepended']) $this->noFramePrepended=1;
223
224 if ($gfxConf['gdlib_2']) {
225 $this->GD2=1;
226 }
227 if ($gfxConf['gdlib_png']) {
228 $this->gifExtension='png';
229 }
230 if ($gfxConf['TTFLocaleConv']) {
231 $this->TTFLocaleConv = $gfxConf['TTFLocaleConv'];
232 }
233 if ($gfxConf['enable_typo3temp_db_tracking']) {
234 $this->enable_typo3temp_db_tracking = $gfxConf['enable_typo3temp_db_tracking'];
235 }
236
237 $this->imageMagickPath = $gfxConf['im_path'];
238 $this->imageFileExt = $gfxConf['imagefile_ext'];
239
240 // This should be set if ImageMagick ver. 5+ is used.
241 if ($gfxConf['im_negate_mask']) {
242 // Boolean. Indicates if the mask images should be inverted first.
243 // This depends of the ImageMagick version. Below ver. 5.1 this should be false.
244 // Above ImageMagick version 5.2+ it should be true.
245 // Just set the flag if the masks works opposite the intension!
246 $this->maskNegate = ' -negate';
247 }
248 if ($gfxConf['im_no_effects']) {
249 // Boolean. This is necessary if using ImageMagick 5+.
250 // Approved version for using effects is version 4.2.9.
251 // Effects in Imagemagick 5+ tends to render very slowly!!
252 // - therefore must be disabled in order not to perform sharpen, blurring and such.
253 $this->NO_IM_EFFECTS = 1;
254
255 $this->cmds['jpg'] = '-colorspace RGB -quality 60';
256 $this->cmds['jpeg'] = '-colorspace RGB -quality 60';
257 }
258 // ... but if 'im_v5effects' is set, dont care about 'im_no_effects'
259 if ($gfxConf['im_v5effects']) {
260 $this->NO_IM_EFFECTS = 0;
261 $this->V5_EFFECTS = 1;
262
263 if ($gfxConf['im_v5effects']>0) {
264 $this->cmds['jpg'] = '-colorspace RGB -quality 60'.$this->v5_sharpen(10);
265 $this->cmds['jpeg'] = '-colorspace RGB -quality 60'.$this->v5_sharpen(10);
266 }
267 }
268
269 if (!$gfxConf['im']) {
270 $this->NO_IMAGE_MAGICK = 1;
271 }
272 // Secures that images are not scaled up.
273 if ($gfxConf['im_noScaleUp']) {
274 $this->mayScaleUp=0;
275 }
276
277 if (TYPO3_MODE=='FE') {
278 $this->csConvObj = &$GLOBALS['TSFE']->csConvObj;
279 } else { // BE assumed:
280 $this->csConvObj = &$GLOBALS['LANG']->csConvObj;
281 }
282 $this->nativeCharset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
283 }
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300 /*************************************************
301 *
302 * Layering images / "IMAGE" GIFBUILDER object
303 *
304 *************************************************/
305
306 /**
307 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is true.
308 * 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
309 * The operation involves ImageMagick for combining.
310 *
311 * @param pointer GDlib image pointer
312 * @param array TypoScript array with configuration for the GIFBUILDER object.
313 * @param array The current working area coordinates.
314 * @return void
315 * @see tslib_gifBuilder::make()
316 */
317 function maskImageOntoImage(&$im,$conf,$workArea) {
318 if ($conf['file'] && $conf['mask']) {
319 $BBimage = $this->imageMagickConvert($conf['file'],$this->gifExtension,'','','','','');
320 $BBmask = $this->imageMagickConvert($conf['mask'],$this->gifExtension,'','','','','');
321 if ($BBimage && $BBmask) {
322 $w = imagesx($im);
323 $h = imagesy($im);
324 $tmpStr = $this->randomName();
325 $theImage = $tmpStr.'_img.'.$this->gifExtension;
326 $theDest = $tmpStr.'_dest.'.$this->gifExtension;
327 $theMask = $tmpStr.'_mask.'.$this->gifExtension;
328 $theMask2 = $tmpStr.'_mask2.'.trim($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_mask_temp_ext_noloss']);
329 // prepare overlay image
330 $cpImg = $this->imageCreateFromGif($BBimage[3]);
331 $destImg = imagecreate($w,$h);
332 ImageColorAllocate($destImg, 0,0,0);
333 $this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
334 $this->ImageGif($destImg, $theImage);
335 imageDestroy($cpImg);
336 imageDestroy($destImg);
337 // prepare mask image
338 $cpImg = $this->imageCreateFromGif($BBmask[3]);
339 $destImg = imagecreate($w,$h);
340 ImageColorAllocate($destImg, 0,0,0);
341 $this->copyGifOntoGif($destImg,$cpImg,$conf,$workArea);
342 $this->ImageGif($destImg, $theMask);
343 imageDestroy($cpImg);
344 imageDestroy($destImg);
345 // treat the mask
346 $this->imageMagickExec($theMask,$theMask2,'-colorspace GRAY'.$this->maskNegate);
347 // mask the images
348 $this->ImageGif($im, $theDest);
349
350 $this->combineExec($theDest,$theImage,$theMask2,$theDest);
351
352 $backIm = $this->imageCreateFromGif($theDest); // The main image is loaded again...
353 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
354 ImageColorTransparent($backIm,-1);
355 $im = $backIm;
356 }
357 // unlink files from process
358 if (!$this->dontUnlinkTempFiles) {
359 unlink($theDest);
360 unlink($theImage);
361 unlink($theMask);
362 unlink($theMask2);
363 }
364 }
365 }
366 }
367
368 /**
369 * Implements the "IMAGE" GIFBUILDER object, when the "mask" property is false (using only $conf['file'])
370 *
371 * @param pointer GDlib image pointer
372 * @param array TypoScript array with configuration for the GIFBUILDER object.
373 * @param array The current working area coordinates.
374 * @return void
375 * @see tslib_gifBuilder::make(), maskImageOntoImage()
376 */
377 function copyImageOntoImage(&$im,$conf,$workArea) {
378 if ($conf['file']) {
379 if ($conf['BBOX'][2]!=$this->gifExtension) {
380 $conf['BBOX']=$this->imageMagickConvert($conf['BBOX'][3],$this->gifExtension,'','','','','');
381 $conf['file']=$conf['BBOX'][3];
382 }
383 $cpImg = $this->imageCreateFromGif($conf['file']);
384 $this->copyGifOntoGif($im,$cpImg,$conf,$workArea);
385 imageDestroy($cpImg);
386 }
387 }
388
389 /**
390 * Copies two GDlib image pointers onto each other, using TypoScript configuration from $conf and the input $workArea definition.
391 *
392 * @param pointer GDlib image pointer, destination (bottom image)
393 * @param pointer GDlib image pointer, source (top image)
394 * @param array TypoScript array with the properties for the IMAGE GIFBUILDER object. Only used for the "tile" property value.
395 * @param array Work area
396 * @return void Works on the $im image pointer
397 * @access private
398 */
399 function copyGifOntoGif(&$im,$cpImg,$conf,$workArea) {
400 $cpW = imagesx($cpImg);
401 $cpH = imagesy($cpImg);
402 $tile = t3lib_div::intExplode(',',$conf['tile']);
403 $tile[0] = t3lib_div::intInRange($tile[0],1,20);
404 $tile[1] = t3lib_div::intInRange($tile[1],1,20);
405 $cpOff = $this->objPosition($conf,$workArea,Array($cpW*$tile[0],$cpH*$tile[1]));
406
407 for ($xt=0;$xt<$tile[0];$xt++) {
408 $Xstart=$cpOff[0]+$cpW*$xt;
409 if ($Xstart+$cpW > $workArea[0]) { // if this image is inside of the workArea, then go on
410 // X:
411 if ($Xstart < $workArea[0]) {
412 $cpImgCutX = $workArea[0]-$Xstart;
413 $Xstart = $workArea[0];
414 } else {
415 $cpImgCutX = 0;
416 }
417 $w = $cpW-$cpImgCutX;
418 if ($Xstart > $workArea[0]+$workArea[2]-$w) {
419 $w = $workArea[0]+$workArea[2]-$Xstart;
420 }
421 if ($Xstart < $workArea[0]+$workArea[2]) { // if this image is inside of the workArea, then go on
422 // Y:
423 for ($yt=0;$yt<$tile[1];$yt++) {
424 $Ystart=$cpOff[1]+$cpH*$yt;
425 if ($Ystart+$cpH > $workArea[1]) { // if this image is inside of the workArea, then go on
426 if ($Ystart < $workArea[1]) {
427 $cpImgCutY = $workArea[1]-$Ystart;
428 $Ystart = $workArea[1];
429 } else {
430 $cpImgCutY = 0;
431 }
432 $h = $cpH-$cpImgCutY;
433 if ($Ystart > $workArea[1]+$workArea[3]-$h) {
434 $h = $workArea[1]+$workArea[3]-$Ystart;
435 }
436 if ($Ystart < $workArea[1]+$workArea[3]) { // if this image is inside of the workArea, then go on
437 $this->imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
438 }
439 }
440 } // Y:
441 }
442 }
443 }
444 }
445
446 /**
447 * Alternative function for using the similat PHP function imagecopyresized(). Used for GD2 only.
448 *
449 * OK, the reason for this stupid fix is the following story:
450 * GD1.x was capable of copying two images together and combining their palettes! GD2 is apparently not.
451 * With GD2 only the palette of the dest-image is used which mostly results in totally black images when trying to
452 * copy a color-ful image onto the destination.
453 * The GD2-fix is to
454 * 1) Create a blank TRUE-COLOR image
455 * 2) Copy the destination image onto that one
456 * 3) Then do the actual operation; Copying the source (top image) onto that
457 * 4) ... and return the result pointer.
458 * 5) Reduce colors (if we do not, the result may become strange!)
459 * It works, but the resulting images is now a true-color PNG which may be very large.
460 * So, why not use 'imagetruecolortopalette ($im, TRUE, 256)' - well because it does NOT WORK! So simple is that.
461 *
462 * For parameters, see PHP function "imagecopyresized()"
463 *
464 * @param pointer see PHP function "imagecopyresized()"
465 * @param pointer see PHP function "imagecopyresized()"
466 * @param integer see PHP function "imagecopyresized()"
467 * @param integer see PHP function "imagecopyresized()"
468 * @param integer see PHP function "imagecopyresized()"
469 * @param integer see PHP function "imagecopyresized()"
470 * @param integer see PHP function "imagecopyresized()"
471 * @param integer see PHP function "imagecopyresized()"
472 * @param integer see PHP function "imagecopyresized()"
473 * @param integer see PHP function "imagecopyresized()"
474 * @return void
475 * @access private
476 * @see t3lib_iconWorks::imagecopyresized()
477 */
478 function imagecopyresized(&$im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h) {
479 if ($this->GD2) {
480 $im_base = imagecreatetruecolor(imagesx($im), imagesy($im)); // Make true color image
481 imagecopyresized($im_base, $im, 0,0,0,0, imagesx($im),imagesy($im),imagesx($im),imagesy($im)); // Copy the source image onto that
482 imagecopyresized($im_base, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h); // Then copy the $cpImg onto that (the actual operation!)
483 $im = $im_base; // Set pointer
484 $this->makeEffect($im, Array('value'=>'colors=256')); // Reduce colors to 256 - make SURE that IM is working then!
485 } else {
486 imagecopyresized($im, $cpImg, $Xstart, $Ystart, $cpImgCutX, $cpImgCutY, $w, $h, $w, $h);
487 }
488 }
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512 /********************************
513 *
514 * Text / "TEXT" GIFBUILDER object
515 *
516 ********************************/
517
518 /**
519 * Implements the "TEXT" GIFBUILDER object
520 *
521 * @param pointer GDlib image pointer
522 * @param array TypoScript array with configuration for the GIFBUILDER object.
523 * @param array The current working area coordinates.
524 * @return void
525 * @see tslib_gifBuilder::make()
526 */
527 function makeText(&$im,$conf,$workArea) {
528 // Spacing
529 $spacing = intval($conf['spacing']);
530 $wordSpacing = intval($conf['wordSpacing']);
531 $wordSpacing = $wordSpacing?$wordSpacing:$spacing*2;
532 // Position
533 $txtPos = $this->txtPosition($conf,$workArea,$conf['BBOX']);
534 $theText = $this->recodeString($conf['text']);
535
536 if ($conf['imgMap'] && is_array($conf['imgMap.'])) {
537 $this->addToMap($this->calcTextCordsForMap($conf['BBOX'][2],$txtPos, $conf['imgMap.']), $conf['imgMap.']);
538 }
539 if (!$conf['hideButCreateMap']) {
540 // Font Color:
541 $cols=$this->convertColor($conf['fontColor']);
542 // NiceText is calculated
543 if (!$conf['niceText']) {
544 // Font Color is reserved:
545 $this->reduceColors($im,256, 200);
546 $Fcolor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
547 // antiAliasing is setup:
548 $Fcolor = ($conf['antiAlias']) ? $Fcolor : -$Fcolor;
549
550 for ($a=0; $a<$conf['iterations']; $a++) {
551 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
552 $this->SpacedImageTTFText($im, $conf['fontSize'], $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText, $spacing, $wordSpacing);
553 } else {
554 ImageTTFText($im, t3lib_div::freetypeDpiComp($conf['fontSize']), $conf['angle'], $txtPos[0], $txtPos[1], $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText);
555 }
556 }
557 } else { // NICETEXT::
558 // options anti_aliased and iterations is NOT available when doing this!!
559 $w = imagesx($im);
560 $h = imagesy($im);
561 $tmpStr = $this->randomName();
562
563 $fileMenu = $tmpStr.'_menuNT.'.$this->gifExtension;
564 $fileColor = $tmpStr.'_colorNT.'.$this->gifExtension;
565 $fileMask = $tmpStr.'_maskNT.'.$this->gifExtension;
566 // Scalefactor
567 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
568 $newW = ceil($sF*imagesx($im));
569 $newH = ceil($sF*imagesy($im));
570
571 // Make mask
572 $maskImg = imagecreate($newW, $newH);
573 ImageColorAllocate($maskImg, 255,255,255);
574 $Fcolor = ImageColorAllocate($maskImg, 0,0,0);
575 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
576 $this->SpacedImageTTFText($maskImg, ceil($sF*$conf['fontSize']), $conf['angle'], ceil($sF*$txtPos[0]), ceil($sF*$txtPos[1]), $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText, ceil($sF*$spacing), ceil($sF*$wordSpacing));
577 } else {
578 ImageTTFText($maskImg, t3lib_div::freetypeDpiComp(ceil($sF*$conf['fontSize'])), $conf['angle'], ceil($sF*$txtPos[0]), ceil($sF*$txtPos[1]), $Fcolor, t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText);
579 }
580 $this->ImageGif($maskImg, $fileMask);
581 ImageDestroy($maskImg);
582
583 // Downscales the mask
584 if ($this->NO_IM_EFFECTS) {
585 if ($this->maskNegate) {
586 $command = trim($this->scalecmd.' '.$w.'x'.$h.'!'); // Negate 2 times makes no negate...
587 } else {
588 $command = trim($this->scalecmd.' '.$w.'x'.$h.'! -negate');
589 }
590 } else {
591 if ($this->maskNegate) {
592 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after']);
593 } else {
594 $command = trim($conf['niceText.']['before'].' '.$this->scalecmd.' '.$w.'x'.$h.'! '.$conf['niceText.']['after'].' -negate');
595 }
596 if ($conf['niceText.']['sharpen']) {
597 if ($this->V5_EFFECTS) {
598 $command.=$this->v5_sharpen($conf['niceText.']['sharpen']);
599 } else {
600 $command.=' -sharpen '.t3lib_div::intInRange($conf['niceText.']['sharpen'],1,99);
601 }
602 }
603 }
604 $this->imageMagickExec($fileMask,$fileMask,$command);
605
606 // Make the color-file
607 $colorImg = imagecreate($w,$h);
608 ImageColorAllocate($colorImg, $cols[0],$cols[1],$cols[2]);
609 $this->ImageGif($colorImg, $fileColor);
610 ImageDestroy($colorImg);
611
612 // The mask is applied
613 $this->ImageGif($im, $fileMenu); // The main pictures is saved temporarily
614
615 $this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);
616
617 $backIm = $this->imageCreateFromGif($fileMenu); // The main image is loaded again...
618 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
619 ImageColorTransparent($backIm,-1);
620 $im = $backIm;
621 }
622
623 // Deleting temporary files;
624 if (!$this->dontUnlinkTempFiles) {
625 unlink($fileMenu);
626 unlink($fileColor);
627 unlink($fileMask);
628 }
629 }
630 }
631 }
632
633 /**
634 * Calculates text position for printing the text onto the image based on configuration like alignment and workarea.
635 *
636 * @param array TypoScript array for the TEXT GIFBUILDER object
637 * @param array Workarea definition
638 * @param array Bounding box information, was set in tslib_gifBuilder::start()
639 * @return array [0]=x, [1]=y, [2]=w, [3]=h
640 * @access private
641 * @see makeText()
642 */
643 function txtPosition($conf,$workArea,$BB) {
644 $bbox = $BB[2];
645 $angle=intval($conf['angle'])/180*pi();
646 $conf['angle']=0;
647 $straightBB = $this->calcBBox($conf);
648
649 // offset, align, valign, workarea
650 $result=Array(); // [0]=x, [1]=y, [2]=w, [3]=h
651 $result[2] = $BB[0];
652 $result[3] = $BB[1];
653 $w=$workArea[2];
654 $h=$workArea[3];
655
656 switch($conf['align']) {
657 case 'right':
658 case 'center':
659 $factor=abs(cos($angle));
660 $sign=(cos($angle)<0)?-1:1;
661 $len1 = $sign*$factor*$straightBB[0];
662 $len2= $sign*$BB[0];
663 $result[0] = $w-ceil($len2*$factor+(1-$factor)*$len1);
664
665 $factor=abs(sin($angle));
666 $sign=(sin($angle)<0)?-1:1;
667 $len1= $sign*$factor*$straightBB[0];
668 $len2= $sign*$BB[1];
669 $result[1]=ceil($len2*$factor+(1-$factor)*$len1);
670 break;
671 }
672 switch($conf['align']) {
673 case 'right':
674 break;
675 case 'center':
676 $result[0] = round(($result[0])/2);
677 $result[1] = round(($result[1])/2);
678 break;
679 default:
680 $result[0]=0;
681 $result[1]=0;
682 break;
683 }
684 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
685 $result = $this->applyOffset($result,$workArea);
686 return $result;
687 }
688
689 /**
690 * Calculates bounding box information for the TEXT GIFBUILDER object.
691 *
692 * @param array TypoScript array for the TEXT GIFBUILDER object
693 * @return array Array with three keys [0]/[1] being x/y and [2] being the bounding box array
694 * @access private
695 * @see txtPosition(), tslib_gifBuilder::start()
696 */
697 function calcBBox($conf) {
698 if (!$conf['niceText']) {
699 $sF = 1;
700 } else { // NICETEXT::
701 $sF = t3lib_div::intInRange($conf['niceText.']['scaleFactor'],2,5);
702 }
703
704 $spacing = intval($conf['spacing']);
705 $wordSpacing = intval($conf['wordSpacing']);
706 $wordSpacing = $wordSpacing?$wordSpacing:$spacing*2;
707
708 $spacing*=$sF;
709 $wordSpacing*=$sF;
710 $theText = $this->recodeString($conf['text']);
711
712 $charInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$conf['fontSize']), $conf['angle'], t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $theText);
713 $theBBoxInfo = $charInf;
714 if ($conf['angle']) {
715 $xArr = Array($charInf[0],$charInf[2],$charInf[4],$charInf[6]);
716 $yArr = Array($charInf[1],$charInf[3],$charInf[5],$charInf[7]);
717 $x=max($xArr)-min($xArr);
718 $y=max($yArr)-min($yArr);
719 } else {
720 $x = ($charInf[2]-$charInf[0]);
721 $y = ($charInf[1]-$charInf[7]);
722 }
723 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
724 $x=0;
725 if (!$spacing && $wordSpacing) {
726 $bits = explode(' ',$theText);
727 while(list(,$word)=each($bits)) {
728 $word.=' ';
729 $wordInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$conf['fontSize']), $conf['angle'], t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $word);
730 $wordW = ($wordInf[2]-$wordInf[0]);
731 $x+=$wordW+$wordSpacing;
732 }
733 } else {
734 $utf8Chars = $this->singleChars($theText);
735 // For each UTF-8 char, do:
736 foreach($utf8Chars as $char) {
737 $charInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($sF*$conf['fontSize']), $conf['angle'], t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $char);
738 $charW = ($charInf[2]-$charInf[0]);
739 $x+=$charW+(($char==' ')?$wordSpacing:$spacing);
740 }
741 }
742 }
743
744 if ($sF>1) {
745 $x = ceil($x/$sF);
746 $y = ceil($y/$sF);
747 if (is_array($theBBoxInfo)) {
748 reset($theBBoxInfo);
749 while(list($key,$val)=each($theBBoxInfo)) {
750 $theBBoxInfo[$key]=ceil($theBBoxInfo[$key]/$sF);
751 }
752 }
753 }
754 return Array($x,$y,$theBBoxInfo);
755 }
756
757 /**
758 * Adds an <area> tag to the internal variable $this->map which is used to accumulate the content for an ImageMap
759 *
760 * @param array Coordinates for a polygon image map as created by ->calcTextCordsForMap()
761 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
762 * @return void
763 * @access private
764 * @see makeText(), calcTextCordsForMap()
765 */
766 function addToMap($cords,$conf) {
767 $JS = $conf['noBlur'] ? '' : ' onfocus="blurLink(this);"';
768
769 $this->map.='<area'.
770 ' shape="poly"'.
771 ' coords="'.implode($cords,',').'"'.
772 ' href="'.htmlspecialchars($conf['url']).'"'.
773 ($conf['target'] ? ' target="'.htmlspecialchars($conf['target']).'"' : '').
774 $JS.
775 (strlen($conf['titleText']) ? ' title="'.htmlspecialchars($conf['titleText']).'"' : '').
776 ' alt="'.htmlspecialchars($conf['altText']).'" />';
777 }
778
779 /**
780 * Calculating the coordinates for a TEXT string on an image map. Used in an <area> tag
781 *
782 * @param array Coordinates (from BBOX array)
783 * @param array Offset array
784 * @param array Configuration for "imgMap." property of a TEXT GIFBUILDER object.
785 * @return array
786 * @access private
787 * @see makeText(), calcTextCordsForMap()
788 */
789 function calcTextCordsForMap($cords,$offset, $conf) {
790 $pars = t3lib_div::intExplode(',',$conf['explode'].',');
791
792 $newCords[0] = $cords[0]+$offset[0]-$pars[0];
793 $newCords[1] = $cords[1]+$offset[1]+$pars[1];
794 $newCords[2] = $cords[2]+$offset[0]+$pars[0];
795 $newCords[3] = $cords[3]+$offset[1]+$pars[1];
796 $newCords[4] = $cords[4]+$offset[0]+$pars[0];
797 $newCords[5] = $cords[5]+$offset[1]-$pars[1];
798 $newCords[6] = $cords[6]+$offset[0]-$pars[0];
799 $newCords[7] = $cords[7]+$offset[1]-$pars[1];
800
801 return $newCords;
802 }
803
804 /**
805 * Printing text onto an image like the PHP function imageTTFText does but in addition it offers options for spacing of letters and words.
806 * Spacing is done by printing one char at a time and this means that the spacing is rather uneven and probably not very nice.
807 * See
808 *
809 * @param pointer (See argument for PHP function imageTTFtext())
810 * @param integer (See argument for PHP function imageTTFtext())
811 * @param integer (See argument for PHP function imageTTFtext())
812 * @param integer (See argument for PHP function imageTTFtext())
813 * @param integer (See argument for PHP function imageTTFtext())
814 * @param integer (See argument for PHP function imageTTFtext())
815 * @param string (See argument for PHP function imageTTFtext())
816 * @param string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in.
817 * @param integer The spacing of letters in pixels
818 * @param integer The spacing of words in pixels
819 * @return void
820 * @access private
821 */
822 function SpacedImageTTFText(&$im, $fontSize, $angle, $x, $y, $Fcolor, $fontFile, $text, $spacing, $wordSpacing) {
823 if (!$spacing && $wordSpacing) {
824 $bits = explode(' ',$text);
825 reset($bits);
826 while(list(,$word)=each($bits)) {
827 $word.=' ';
828 $word = $word;
829 $wordInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($fontSize), $angle, t3lib_stdGraphic::prependAbsolutePath($fontFile), $word);
830 $wordW = ($wordInf[2]-$wordInf[0]);
831 ImageTTFText($im, t3lib_div::freetypeDpiComp($fontSize), $angle, $x, $y, $Fcolor, t3lib_stdGraphic::prependAbsolutePath($fontFile), $word);
832 $x+=$wordW+$wordSpacing;
833 }
834 } else {
835 $utf8Chars = $this->singleChars($text);
836 // For each UTF-8 char, do:
837 foreach($utf8Chars as $char) {
838 $charInf = ImageTTFBBox(t3lib_div::freetypeDpiComp($fontSize), $angle, t3lib_stdGraphic::prependAbsolutePath($fontFile), $char);
839 $charW = ($charInf[2]-$charInf[0]);
840 ImageTTFText($im, t3lib_div::freetypeDpiComp($fontSize), $angle, $x, $y, $Fcolor, t3lib_stdGraphic::prependAbsolutePath($fontFile), $char);
841 $x+=$charW+(($char==' ')?$wordSpacing:$spacing);
842 }
843 }
844 }
845
846 /**
847 * Function that finds the right fontsize that will render the textstring within a certain width
848 *
849 * @param array The TypoScript properties of the TEXT GIFBUILDER object
850 * @return integer The new fontSize
851 * @access private
852 * @author Rene Fritz <r.fritz@colorcube.de>
853 * @see tslib_gifBuilder::start()
854 */
855 function fontResize($conf) {
856 // 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!!!!
857 $maxWidth = intval($conf['maxWidth']);
858 if ($maxWidth) {
859 if ($spacing || $wordSpacing) { // If any kind of spacing applys, we use this function:
860 return $conf['fontSize'];
861 // ################ no calc for spacing yet !!!!!!
862 } else {
863 $fontSize = $conf['fontSize'];
864 do {
865 $conf['fontSize'] = $fontSize;
866 // determine bounding box.
867 $bounds = ImageTTFBBox(t3lib_div::freetypeDpiComp($conf['fontSize']), $conf['angle'], t3lib_stdGraphic::prependAbsolutePath($conf['fontFile']), $this->recodeString($conf['text']));
868 if ($conf['angle']< 0) {
869 $pixelWidth = abs($bounds[4]-$bounds[0]);
870 } elseif ($conf['angle'] > 0) {
871 $pixelWidth = abs($bounds[2]-$bounds[6]);
872 } else {
873 $pixelWidth = abs($bounds[4]-$bounds[6]);
874 }
875 // This is a very raw calculation but it makes it in one step
876 $fontSize=(int)($maxWidth*$fontSize/$pixelWidth);
877 if ($fontSize >= $conf['fontSize']) {
878 $fontSize = $conf['fontSize']-1;
879 }
880 } while ($pixelWidth > $maxWidth);
881 }//if spacing
882 }
883 return $conf['fontSize'];
884 }
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901 /*********************************************
902 *
903 * Other GIFBUILDER objects related to TEXT
904 *
905 *********************************************/
906
907 /**
908 * Implements the "OUTLINE" GIFBUILDER object / property for the TEXT object
909 *
910 * @param pointer GDlib image pointer
911 * @param array TypoScript array with configuration for the GIFBUILDER object.
912 * @param array The current working area coordinates.
913 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
914 * @return void
915 * @see tslib_gifBuilder::make(), makeText()
916 */
917 function makeOutline(&$im,$conf,$workArea,$txtConf) {
918 $thickness = intval($conf['thickness']);
919 if ($thickness) {
920 $txtConf['fontColor'] = $conf['color'];
921 $outLineDist = t3lib_div::intInRange($thickness,1,2);
922 for ($b=1;$b<=$outLineDist;$b++) {
923 if ($b==1) {
924 $it = 8;
925 } else {
926 $it = 16;
927 }
928 $outL = $this->circleOffset($b, $it);
929 for ($a=0;$a<$it;$a++) {
930 $this->makeText($im,$txtConf,$this->applyOffset($workArea,$outL[$a]));
931 }
932 }
933 }
934 }
935
936 /**
937 * Creates some offset values in an array used to simulate a circularly applied outline around TEXT
938 *
939 * access private
940 *
941 * @param integer Distance
942 * @param integer Iterations.
943 * @return array
944 * @see makeOutline()
945 */
946 function circleOffset($distance, $iterations) {
947 $res = Array();
948 if ($distance && $iterations) {
949 for ($a=0;$a<$iterations;$a++) {
950 $yOff = round(sin(2*pi()/$iterations*($a+1))*100*$distance);
951 if ($yOff) {$yOff = intval(ceil(abs($yOff/100))*($yOff/abs($yOff)));}
952 $xOff = round(cos(2*pi()/$iterations*($a+1))*100*$distance);
953 if ($xOff) {$xOff = intval(ceil(abs($xOff/100))*($xOff/abs($xOff)));}
954 $res[$a] = Array($xOff,$yOff);
955 }
956 }
957 return $res;
958 }
959
960 /**
961 * Implements the "EMBOSS" GIFBUILDER object / property for the TEXT object
962 *
963 * @param pointer GDlib image pointer
964 * @param array TypoScript array with configuration for the GIFBUILDER object.
965 * @param array The current working area coordinates.
966 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
967 * @return void
968 * @see tslib_gifBuilder::make(), makeShadow()
969 */
970 function makeEmboss(&$im,$conf,$workArea,$txtConf) {
971 $conf['color']=$conf['highColor'];
972 $this->makeShadow($im,$conf,$workArea,$txtConf);
973 $newOffset = t3lib_div::intExplode(',',$conf['offset']);
974 $newOffset[0]*=-1;
975 $newOffset[1]*=-1;
976 $conf['offset']=implode($newOffset,',');
977 $conf['color']=$conf['lowColor'];
978 $this->makeShadow($im,$conf,$workArea,$txtConf);
979 }
980
981 /**
982 * Implements the "SHADOW" GIFBUILDER object / property for the TEXT object
983 * The operation involves ImageMagick for combining.
984 *
985 * @param pointer GDlib image pointer
986 * @param array TypoScript array with configuration for the GIFBUILDER object.
987 * @param array The current working area coordinates.
988 * @param array TypoScript array with configuration for the associated TEXT GIFBUILDER object.
989 * @return void
990 * @see tslib_gifBuilder::make(), makeText(), makeEmboss()
991 */
992 function makeShadow(&$im,$conf,$workArea,$txtConf) {
993 $workArea = $this->applyOffset($workArea,t3lib_div::intExplode(',',$conf['offset']));
994 $blurRate = t3lib_div::intInRange(intval($conf['blur']),0,99);
995
996 if (!$blurRate || $this->NO_IM_EFFECTS) { // No effects if ImageMagick ver. 5+
997 $txtConf['fontColor'] = $conf['color'];
998 $this->makeText($im,$txtConf,$workArea);
999 } else {
1000 $w = imagesx($im);
1001 $h = imagesy($im);
1002 $blurBorder= 3; // area around the blur used for cropping something
1003 $tmpStr = $this->randomName();
1004 $fileMenu = $tmpStr.'_menu.'.$this->gifExtension;
1005 $fileColor = $tmpStr.'_color.'.$this->gifExtension;
1006 $fileMask = $tmpStr.'_mask.'.$this->gifExtension;
1007
1008 // BlurColor Image laves
1009 $blurColImg = imagecreate($w,$h);
1010 $bcols=$this->convertColor($conf['color']);
1011 ImageColorAllocate($blurColImg, $bcols[0],$bcols[1],$bcols[2]);
1012 $this->ImageGif($blurColImg, $fileColor);
1013 ImageDestroy($blurColImg);
1014
1015 // The mask is made: BlurTextImage
1016 $blurTextImg = imagecreate($w+$blurBorder*2,$h+$blurBorder*2);
1017 ImageColorAllocate($blurTextImg, 0,0,0); // black background
1018 $txtConf['fontColor'] = 'white';
1019 $blurBordArr = Array($blurBorder,$blurBorder);
1020 $this->makeText($blurTextImg,$txtConf, $this->applyOffset($workArea,$blurBordArr));
1021 $this->ImageGif($blurTextImg, $fileMask); // dump to temporary file
1022 ImageDestroy($blurTextImg); // destroy
1023
1024
1025 $command='';
1026 $command.=$this->maskNegate;
1027
1028 if ($this->V5_EFFECTS) {
1029 $command.=$this->v5_blur($blurRate+1);
1030 } else {
1031 // Blurring of the mask
1032 $times = ceil($blurRate/10); // How many blur-commands that is executed. Min = 1;
1033 $newBlurRate = $blurRate*4; // Her booster vi blur-rate, så at den allerede ved 25 er på 100. Resten op til 99 går på iterationer af blur-kommandoen
1034 $newBlurRate = t3lib_div::intInRange($newBlurRate,1,99);
1035 for ($a=0;$a<$times;$a++) { // Building blur-command
1036 $command.=' -blur '.$blurRate;
1037 }
1038 }
1039
1040 $this->imageMagickExec($fileMask,$fileMask,$command);
1041
1042 $blurTextImg_tmp = $this->imageCreateFromGif($fileMask); // the mask is loaded again
1043 if ($blurTextImg_tmp) { // if nothing went wrong we continue with the blurred mask
1044
1045 // cropping the border from the mask
1046 $blurTextImg = imagecreate($w,$h);
1047 $this->imagecopyresized($blurTextImg, $blurTextImg_tmp, 0, 0, $blurBorder, $blurBorder, $w, $h, $w, $h);
1048 ImageDestroy($blurTextImg_tmp); // Destroy the temporary mask
1049
1050 // adjust the mask
1051 $intensity = 40;
1052 if ($conf['intensity']) {
1053 $intensity = t3lib_div::intInRange($conf['intensity'],0,100);
1054 }
1055 $intensity = ceil(255-($intensity/100*255));
1056 $this->inputLevels($blurTextImg,0,$intensity,$this->maskNegate);
1057
1058 $opacity = t3lib_div::intInRange(intval($conf['opacity']),0,100);
1059 if ($opacity && $opacity<100) {
1060 $high = ceil(255*$opacity/100);
1061 $this->outputLevels($blurTextImg,0,$high,$this->maskNegate); // reducing levels as the opacity demands
1062 }
1063
1064 $this->ImageGif($blurTextImg, $fileMask); // Dump the mask again
1065 ImageDestroy($blurTextImg); // Destroy the mask
1066
1067 // The pictures are combined
1068 $this->ImageGif($im, $fileMenu); // The main pictures is saved temporarily
1069
1070 $this->combineExec($fileMenu,$fileColor,$fileMask,$fileMenu);
1071
1072 $backIm = $this->imageCreateFromGif($fileMenu); // The main image is loaded again...
1073 if ($backIm) { // ... and if nothing went wrong we load it onto the old one.
1074 ImageColorTransparent($backIm,-1);
1075 $im = $backIm;
1076 }
1077 }
1078 // Deleting temporary files;
1079 if (!$this->dontUnlinkTempFiles) {
1080 unlink($fileMenu);
1081 unlink($fileColor);
1082 unlink($fileMask);
1083 }
1084 }
1085 }
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107 /****************************
1108 *
1109 * Other GIFBUILDER objects
1110 *
1111 ****************************/
1112
1113 /**
1114 * Implements the "BOX" GIFBUILDER object
1115 *
1116 * @param pointer GDlib image pointer
1117 * @param array TypoScript array with configuration for the GIFBUILDER object.
1118 * @param array The current working area coordinates.
1119 * @return void
1120 * @see tslib_gifBuilder::make()
1121 */
1122 function makeBox(&$im,$conf,$workArea) {
1123 $cords = t3lib_div::intExplode(',',$conf['dimensions'].',,,');
1124 $conf['offset']=$cords[0].','.$cords[1];
1125 $cords = $this->objPosition($conf,$workArea,Array($cords[2],$cords[3]));
1126 $cols=$this->convertColor($conf['color']);
1127 $this->reduceColors($im,256, 255);
1128 $tmpColor = ImageColorAllocate($im, $cols[0],$cols[1],$cols[2]);
1129 imagefilledrectangle($im, $cords[0], $cords[1], $cords[0]+$cords[2]-1, $cords[1]+$cords[3]-1, $tmpColor);
1130 }
1131
1132 /**
1133 * Implements the "EFFECT" GIFBUILDER object
1134 * The operation involves ImageMagick for applying effects
1135 *
1136 * @param pointer GDlib image pointer
1137 * @param array TypoScript array with configuration for the GIFBUILDER object.
1138 * @return void
1139 * @see tslib_gifBuilder::make(), applyImageMagickToPHPGif()
1140 */
1141 function makeEffect(&$im, $conf) {
1142 $commands = $this->IMparams($conf['value']);
1143 if ($commands) {
1144 $this->applyImageMagickToPHPGif($im, $commands);
1145 }
1146 }
1147
1148 /**
1149 * Creating ImageMagick paramters from TypoScript property
1150 *
1151 * @param string A string with effect keywords=value pairs separated by "|"
1152 * @return string ImageMagick prepared parameters.
1153 * @access private
1154 * @see makeEffect()
1155 */
1156 function IMparams($setup) {
1157 if (!trim($setup)){return '';}
1158 $effects = explode('|', $setup);
1159 $commands = '';
1160 while(list(,$val)=each($effects)) {
1161 $pairs=explode('=',$val,2);
1162 $value = trim($pairs[1]);
1163 $effect = strtolower(trim($pairs[0]));
1164 switch($effect) {
1165 case 'gamma':
1166 $commands.=' -gamma '.doubleval($value);
1167 break;
1168 case 'blur':
1169 if (!$this->NO_IM_EFFECTS) {
1170 if ($this->V5_EFFECTS) {
1171 $commands.=$this->v5_blur($value);
1172 } else {
1173 $commands.=' -blur '.t3lib_div::intInRange($value,1,99);
1174 }
1175 }
1176 break;
1177 case 'sharpen':
1178 if (!$this->NO_IM_EFFECTS) {
1179 if ($this->V5_EFFECTS) {
1180 $commands.=$this->v5_sharpen($value);
1181 } else {
1182 $commands.=' -sharpen '.t3lib_div::intInRange($value,1,99);
1183 }
1184 }
1185 break;
1186 case 'rotate':
1187 $commands.=' -rotate '.t3lib_div::intInRange($value,0,360);
1188 break;
1189 case 'solarize':
1190 $commands.=' -solarize '.t3lib_div::intInRange($value,0,99);
1191 break;
1192 case 'swirl':
1193 $commands.=' -swirl '.t3lib_div::intInRange($value,0,1000);
1194 break;
1195 case 'wave':
1196 $params = t3lib_div::intExplode(',',$value);
1197 $commands.=' -wave '.t3lib_div::intInRange($params[0],0,99).'x'.t3lib_div::intInRange($params[1],0,99);
1198 break;
1199 case 'charcoal':
1200 $commands.=' -charcoal '.t3lib_div::intInRange($value,0,100);
1201 break;
1202 case 'gray':
1203 $commands.=' -colorspace GRAY';
1204 break;
1205 case 'edge':
1206 $commands.=' -edge '.t3lib_div::intInRange($value,0,99);
1207 break;
1208 case 'emboss':
1209 $commands.=' -emboss';
1210 break;
1211 case 'flip':
1212 $commands.=' -flip';
1213 break;
1214 case 'flop':
1215 $commands.=' -flop';
1216 break;
1217 case 'colors':
1218 $commands.=' -colors '.t3lib_div::intInRange($value,2,255);
1219 break;
1220 case 'shear':
1221 $commands.=' -shear '.t3lib_div::intInRange($value,-90,90);
1222 break;
1223 case 'invert':
1224 $commands.=' -negate';
1225 break;
1226 }
1227 }
1228 return $commands;
1229 }
1230
1231 /**
1232 * Implements the "ADJUST" GIFBUILDER object
1233 *
1234 * @param pointer GDlib image pointer
1235 * @param array TypoScript array with configuration for the GIFBUILDER object.
1236 * @return void
1237 * @see tslib_gifBuilder::make(), autoLevels(), outputLevels(), inputLevels()
1238 */
1239 function adjust(&$im, $conf) {
1240 $setup = $conf['value'];
1241 if (!trim($setup)){return '';}
1242 $effects = explode('|', $setup);
1243 while(list(,$val)=each($effects)) {
1244 $pairs=explode('=',$val,2);
1245 $value = trim($pairs[1]);
1246 $effect = strtolower(trim($pairs[0]));
1247 switch($effect) {
1248 case 'inputlevels': // low,high
1249 $params = t3lib_div::intExplode(',',$value);
1250 $this->inputLevels($im,$params[0],$params[1]);
1251 break;
1252 case 'outputlevels':
1253 $params = t3lib_div::intExplode(',',$value);
1254 $this->outputLevels($im,$params[0],$params[1]);
1255 break;
1256 case 'autolevels':
1257 $this->autoLevels($im);
1258 break;
1259 }
1260 }
1261 }
1262
1263 /**
1264 * Implements the "CROP" GIFBUILDER object
1265 *
1266 * @param pointer GDlib image pointer
1267 * @param array TypoScript array with configuration for the GIFBUILDER object.
1268 * @return void
1269 * @see tslib_gifBuilder::make()
1270 */
1271 function crop(&$im,$conf) {
1272 $this->setWorkArea(''); // clears workArea to total image
1273 $cords = t3lib_div::intExplode(',',$conf['crop'].',,,');
1274 $conf['offset']=$cords[0].','.$cords[1];
1275 $cords = $this->objPosition($conf,$this->workArea,Array($cords[2],$cords[3]));
1276
1277 $newIm = imagecreate($cords[2],$cords[3]);
1278 $cols=$this->convertColor($conf['backColor']?$conf['backColor']:$this->setup['backColor']);
1279 ImageColorAllocate($newIm, $cols[0],$cols[1],$cols[2]);
1280
1281 $newConf = Array();
1282 $workArea = Array(0,0,$cords[2],$cords[3]);
1283 if ($cords[0]<0) {$workArea[0]=abs($cords[0]);} else {$newConf['offset']=-$cords[0];}
1284 if ($cords[1]<0) {$workArea[1]=abs($cords[1]);} else {$newConf['offset'].=','.-$cords[1];}
1285
1286 $this->copyGifOntoGif($newIm,$im,$newConf,$workArea);
1287 $im = $newIm;
1288 $this->w = imagesx($im);
1289 $this->h = imagesy($im);
1290 $this->setWorkArea(''); // clears workArea to total image
1291 }
1292
1293 /**
1294 * Implements the "SCALE" GIFBUILDER object
1295 *
1296 * @param pointer GDlib image pointer
1297 * @param array TypoScript array with configuration for the GIFBUILDER object.
1298 * @return void
1299 * @see tslib_gifBuilder::make()
1300 */
1301 function scale(&$im,$conf) {
1302 if ($conf['width'] || $conf['height'] || $conf['params']) {
1303 $tmpStr = $this->randomName();
1304 $theFile = $tmpStr.'.'.$this->gifExtension;
1305 $this->ImageGif($im, $theFile);
1306 $theNewFile = $this->imageMagickConvert($theFile,$this->gifExtension,$conf['width'],$conf['height'],$conf['params'],'','');
1307 $tmpImg = $this->imageCreateFromGif($theNewFile[3]);
1308 if ($tmpImg) {
1309 ImageDestroy($im);
1310 $im = $tmpImg;
1311 $this->w = imagesx($im);
1312 $this->h = imagesy($im);
1313 $this->setWorkArea(''); // clears workArea to total image
1314 }
1315 if (!$this->dontUnlinkTempFiles) {
1316 unlink($theFile);
1317 if ($theNewFile[3] && $theNewFile[3]!=$theFile) {
1318 unlink($theNewFile[3]);
1319 }
1320 }
1321 }
1322 }
1323
1324 /**
1325 * Implements the "WORKAREA" GIFBUILDER object when setting it
1326 * Setting internal working area boundaries (->workArea)
1327 *
1328 * @param string Working area dimensions, comma separated
1329 * @return void
1330 * @access private
1331 * @see tslib_gifBuilder::make()
1332 */
1333 function setWorkArea($workArea) {
1334 $this->workArea = t3lib_div::intExplode(',',$workArea);
1335 $this->workArea = $this->applyOffset($this->workArea,$this->OFFSET);
1336 if (!$this->workArea[2]) {$this->workArea[2]=$this->w;}
1337 if (!$this->workArea[3]) {$this->workArea[3]=$this->h;}
1338 }
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362 /*************************
1363 *
1364 * Adjustment functions
1365 *
1366 ************************/
1367
1368 /**
1369 * Apply auto-levels to input image pointer
1370 *
1371 * @param integer GDlib Image Pointer
1372 * @return void
1373 */
1374 function autolevels(&$im) {
1375 $totalCols = ImageColorsTotal($im);
1376 $min=255;
1377 $max=0;
1378 for ($c=0; $c<$totalCols; $c++) {
1379 $cols = ImageColorsForIndex($im,$c);
1380 $grayArr[] = round(($cols['red']+$cols['green']+$cols['blue'])/3);
1381 }
1382 $min=min($grayArr);
1383 $max=max($grayArr);
1384 $delta = $max-$min;
1385 if ($delta) {
1386 for ($c=0; $c<$totalCols; $c++) {
1387 $cols = ImageColorsForIndex($im,$c);
1388 $cols['red'] = floor(($cols['red']-$min)/$delta*255);
1389 $cols['green'] = floor(($cols['green']-$min)/$delta*255);
1390 $cols['blue'] = floor(($cols['blue']-$min)/$delta*255);
1391 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1392 }
1393 }
1394 }
1395
1396 /**
1397 * Apply output levels to input image pointer (decreasing contrast)
1398 *
1399 * @param integer GDlib Image Pointer
1400 * @param integer The "low" value (close to 0)
1401 * @param integer The "high" value (close to 255)
1402 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1403 * @return void
1404 */
1405 function outputLevels(&$im,$low,$high,$swap='') {
1406 if ($low<$high){
1407 $low = t3lib_div::intInRange($low,0,255);
1408 $high = t3lib_div::intInRange($high,0,255);
1409
1410 if ($swap) {
1411 $temp = $low;
1412 $low = 255-$high;
1413 $high = 255-$temp;
1414 }
1415
1416 $delta = $high-$low;
1417 $totalCols = ImageColorsTotal($im);
1418 for ($c=0; $c<$totalCols; $c++) {
1419 $cols = ImageColorsForIndex($im,$c);
1420 $cols['red'] = $low+floor($cols['red']/255*$delta);
1421 $cols['green'] = $low+floor($cols['green']/255*$delta);
1422 $cols['blue'] = $low+floor($cols['blue']/255*$delta);
1423 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1424 }
1425 }
1426 }
1427
1428 /**
1429 * Apply input levels to input image pointer (increasing contrast)
1430 *
1431 * @param integer GDlib Image Pointer
1432 * @param integer The "low" value (close to 0)
1433 * @param integer The "high" value (close to 255)
1434 * @param boolean If swap, then low and high are swapped. (Useful for negated masks...)
1435 * @return void
1436 */
1437 function inputLevels(&$im,$low,$high,$swap='') {
1438 if ($low<$high){
1439 $low = t3lib_div::intInRange($low,0,255);
1440 $high = t3lib_div::intInRange($high,0,255);
1441
1442 if ($swap) {
1443 $temp = $low;
1444 $low = 255-$high;
1445 $high = 255-$temp;
1446 }
1447
1448 $delta = $high-$low;
1449 $totalCols = ImageColorsTotal($im);
1450 for ($c=0; $c<$totalCols; $c++) {
1451 $cols = ImageColorsForIndex($im,$c);
1452 $cols['red'] = t3lib_div::intInRange(($cols['red']-$low)/$delta*255, 0,255);
1453 $cols['green'] = t3lib_div::intInRange(($cols['green']-$low)/$delta*255, 0,255);
1454 $cols['blue'] = t3lib_div::intInRange(($cols['blue']-$low)/$delta*255, 0,255);
1455 ImageColorSet($im,$c,$cols['red'],$cols['green'],$cols['blue']);
1456 }
1457 }
1458 }
1459
1460 /**
1461 * Reduce colors in image
1462 *
1463 * @param integer GDlib Image Pointer
1464 * @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.
1465 * @param integer Number of colors to reduce the image to.
1466 * @return void
1467 */
1468 function reduceColors(&$im,$limit, $cols) {
1469 if (ImageColorsTotal($im)>=$limit) {
1470 $this->makeEffect($im, Array('value'=>'colors='.$cols) );
1471 }
1472 }
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492 /*********************************
1493 *
1494 * GIFBUILDER Helper functions
1495 *
1496 *********************************/
1497
1498 /**
1499 * Checks if the $fontFile is already at an absolute path and if not, prepends the correct path.
1500 * Use PATH_site unless we are in the backend.
1501 * Call it by t3lib_stdGraphic::prependAbsolutePath()
1502 *
1503 * @param string The font file
1504 * @return string The font file with absolute path.
1505 */
1506 function prependAbsolutePath($fontFile) {
1507 $absPath = defined('PATH_typo3') ? dirname(PATH_thisScript).'/' :PATH_site;
1508 $fontFile = t3lib_div::isAbsPath($fontFile) ? $fontFile : $absPath.$fontFile;
1509 return $fontFile;
1510 }
1511
1512 /**
1513 * Returns the IM command for sharpening with ImageMagick 5 (when $this->V5_EFFECTS is set).
1514 * Uses $this->im5fx_sharpenSteps for translation of the factor to an actual command.
1515 *
1516 * @param integer The sharpening factor, 0-100 (effectively in 10 steps)
1517 * @return string The sharpening command, eg. " -sharpen 3x4"
1518 * @see makeText(), IMparams(), v5_blur()
1519 */
1520 function v5_sharpen($factor) {
1521 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
1522
1523 $sharpenArr=explode(',',','.$this->im5fx_sharpenSteps);
1524 $sharpenF= trim($sharpenArr[$factor]);
1525 if ($sharpenF) {
1526 $cmd = ' -sharpen '.$sharpenF;
1527 return $cmd;
1528 }
1529 }
1530
1531 /**
1532 * Returns the IM command for blurring with ImageMagick 5 (when $this->V5_EFFECTS is set).
1533 * Uses $this->im5fx_blurSteps for translation of the factor to an actual command.
1534 *
1535 * @param integer The blurring factor, 0-100 (effectively in 10 steps)
1536 * @return string The blurring command, eg. " -blur 3x4"
1537 * @see makeText(), IMparams(), v5_sharpen()
1538 */
1539 function v5_blur($factor) {
1540 $factor = t3lib_div::intInRange(ceil($factor/10),0,10);
1541
1542 $blurArr=explode(',',','.$this->im5fx_blurSteps);
1543 $blurF= trim($blurArr[$factor]);
1544 if ($blurF) {
1545 $cmd=' -blur '.$blurF;
1546 return $cmd;
1547 }
1548 }
1549
1550 /**
1551 * Returns a random filename prefixed with "temp_" and then 32 char md5 hash (without extension) from $this->tempPath.
1552 * 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.
1553 *
1554 * @return string
1555 */
1556 function randomName() {
1557 return $this->tempPath.'temp_'.md5(uniqid(''));
1558 }
1559
1560 /**
1561 * Applies offset value to coordinated in $cords.
1562 * Basically the value of key 0/1 of $OFFSET is added to keys 0/1 of $cords
1563 *
1564 * @param array Integer coordinates in key 0/1
1565 * @param array Offset values in key 0/1
1566 * @return array Modified $cords array
1567 */
1568 function applyOffset($cords,$OFFSET) {
1569 $cords[0] = intval($cords[0])+intval($OFFSET[0]);
1570 $cords[1] = intval($cords[1])+intval($OFFSET[1]);
1571 return $cords;
1572 }
1573
1574 /**
1575 * Converts a "HTML-color" TypoScript datatype to RGB-values.
1576 * Default is 0,0,0
1577 *
1578 * @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
1579 * @return array RGB values in key 0/1/2 of the array
1580 */
1581 function convertColor($string) {
1582 $col=array();
1583 $cParts = explode(':',$string,2);
1584
1585 // Finding the RGB definitions of the color:
1586 $string=$cParts[0];
1587 if (strstr($string,'#')) {
1588 $string = ereg_replace('[^A-Fa-f0-9]*','',$string);
1589 $col[]=HexDec(substr($string,0,2));
1590 $col[]=HexDec(substr($string,2,2));
1591 $col[]=HexDec(substr($string,4,2));
1592 } elseif (strstr($string,',')) {
1593 $string = ereg_replace('[^,0-9]*','',$string);
1594 $strArr = explode(',',$string);
1595 $col[]=intval($strArr[0]);
1596 $col[]=intval($strArr[1]);
1597 $col[]=intval($strArr[2]);
1598 } else {
1599 $string = strtolower(trim($string));
1600 if ($this->colMap[$string]) {
1601 $col = $this->colMap[$string];
1602 } else {
1603 $col = Array(0,0,0);
1604 }
1605 }
1606 // ... and possibly recalculating the value
1607 if (trim($cParts[1])) {
1608 $cParts[1]=trim($cParts[1]);
1609 if (substr($cParts[1],0,1)=='*') {
1610 $val=doubleval(substr($cParts[1],1));
1611 $col[0]=t3lib_div::intInRange($col[0]*$val,0,255);
1612 $col[1]=t3lib_div::intInRange($col[1]*$val,0,255);
1613 $col[2]=t3lib_div::intInRange($col[2]*$val,0,255);
1614 } else {
1615 $val=intval($cParts[1]);
1616 $col[0]=t3lib_div::intInRange($col[0]+$val,0,255);
1617 $col[1]=t3lib_div::intInRange($col[1]+$val,0,255);
1618 $col[2]=t3lib_div::intInRange($col[2]+$val,0,255);
1619 }
1620 }
1621 return $col;
1622 }
1623
1624 /**
1625 * Recode string
1626 * Used with text strings for fonts when languages has other character sets.
1627 *
1628 * @param string The text to recode
1629 * @return string The recoded string. Should be UTF-8 output. MAY contain entities (eg. &#123; or &#quot; which should render as real chars).
1630 */
1631 function recodeString($string) {
1632 // Recode string to UTF-8 from $this->nativeCharset:
1633 if ($this->nativeCharset && $this->nativeCharset!='utf-8') {
1634 $string = $this->csConvObj->utf8_encode($string,$this->nativeCharset); // Convert to UTF-8
1635 }
1636
1637 // Recode string accoding to TTFLocaleConv. Depreciated.
1638 if ($this->TTFLocaleConv) {
1639 $string = recode_string($this->TTFLocaleConv,$string);
1640 }
1641
1642 return $string;
1643 }
1644
1645 /**
1646 * Split a string into an array of individual characters
1647 * 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.
1648 *
1649 * @param string The text string to spli
1650 * @return array Numerical array with a char as each value.
1651 */
1652 function singleChars($theText) {
1653 if ($this->nativeCharset) {
1654 return $this->csConvObj->utf8_to_numberarray($theText,1,1); // Get an array of separated UTF-8 chars
1655 } else {
1656 $output=array();
1657 $c=strlen($theText);
1658 for($a=0;$a<$c;$a++) {
1659 $output[]=substr($theText,$a,1);
1660 }
1661 return $output;
1662 }
1663 }
1664
1665 /**
1666 * 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
1667 *
1668 * @param array TypoScript configuration for a GIFBUILDER object
1669 * @param array Workarea definition
1670 * @param array BB (Bounding box) array. Not just used for TEXT objects but also for others
1671 * @return array [0]=x, [1]=y, [2]=w, [3]=h
1672 * @access private
1673 * @see copyGifOntoGif(), makeBox(), crop()
1674 */
1675 function objPosition($conf,$workArea,$BB) {
1676 // offset, align, valign, workarea
1677 $result=Array();
1678 $result[2] = $BB[0];
1679 $result[3] = $BB[1];
1680 $w=$workArea[2];
1681 $h=$workArea[3];
1682
1683 $align = explode(',',$conf['align']);
1684 $align[0] = strtolower(substr(trim($align[0]),0,1));
1685 $align[1] = strtolower(substr(trim($align[1]),0,1));
1686
1687 switch($align[0]) {
1688 case 'r':
1689 $result[0]=$w-$result[2];
1690 break;
1691 case 'c':
1692 $result[0] = round(($w-$result[2])/2);
1693 break;
1694 default:
1695 $result[0] = 0;
1696 break;
1697 }
1698 switch($align[1]) {
1699 case 'b':
1700 $result[1] = $h-$result[3]; // y pos
1701 break;
1702 case 'c':
1703 $result[1] = round(($h-$result[3])/2);
1704 break;
1705 default:
1706 $result[1]=0;
1707 break;
1708 }
1709 $result = $this->applyOffset($result,t3lib_div::intExplode(',',$conf['offset']));
1710 $result = $this->applyOffset($result,$workArea);
1711 return $result;
1712 }
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734 /***********************************
1735 *
1736 * Scaling, Dimensions of images
1737 *
1738 ***********************************/
1739
1740 /**
1741 * Converts $imagefile to another file in temp-dir of type $newExt (extension).
1742 *
1743 * @param string The image filepath
1744 * @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.
1745 * @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
1746 * @param string Height. See $w
1747 * @param string Additional ImageMagick parameters.
1748 * @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...
1749 * @param array An array with options passed to getImageScale (see this function).
1750 * @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.
1751 * @return array [0]/[1] is w/h, [2] is file extension and [3] is the filename.
1752 * @see getImageScale(), typo3/show_item.php, fileList_ext::renderImage(), tslib_cObj::getImgResource(), SC_tslib_showpic::show(), maskImageOntoImage(), copyImageOntoImage(), scale()
1753 */
1754 function imageMagickConvert($imagefile,$newExt='',$w='',$h='',$params='',$frame='',$options='',$mustCreate=0) {
1755 if ($this->NO_IMAGE_MAGICK) {
1756 // Returning file info right away
1757 return $this->getImageDimensions($imagefile);
1758 }
1759
1760 if($info=$this->getImageDimensions($imagefile)) {
1761 $newExt=strtolower(trim($newExt));
1762 if (!$newExt) { // If no extension is given the original extension is used
1763 $newExt = $info[2];
1764 }
1765 if ($newExt=='web') {
1766 if (t3lib_div::inList($this->webImageExt,$info[2])) {
1767 $newExt = $info[2];
1768 } else {
1769 $newExt = $this->gif_or_jpg($info[2],$info[0],$info[1]);
1770 if (!$params) {
1771 $params = $this->cmds[$newExt];
1772 }
1773 }
1774 }
1775 if (t3lib_div::inList($this->imageFileExt,$newExt)) {
1776 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
1777
1778 $data = $this->getImageScale($info,$w,$h,$options);
1779 $w=$data['origW'];
1780 $h=$data['origH'];
1781
1782 // if no convertion should be performed
1783 $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....
1784
1785 if ($wh_noscale && !$params && !$frame && $newExt==$info[2] && !$mustCreate) {
1786 $info[3] = $imagefile;
1787 return $info;
1788 }
1789 $info[0]=$data[0];
1790 $info[1]=$data[1];
1791
1792 $frame = $this->noFramePrepended ? '' : '['.intval($frame).']';
1793
1794 if (!$params) {
1795 $params = $this->cmds[$newExt];
1796 }
1797
1798 $command = $this->scalecmd.' '.$info[0].'x'.$info[1].'! '.$params.' ';
1799
1800 if ($this->alternativeOutputKey) {
1801 $theOutputName = t3lib_div::shortMD5($command.basename($imagefile).$this->alternativeOutputKey.$frame);
1802 } else {
1803 $theOutputName = t3lib_div::shortMD5($command.$imagefile.filemtime($imagefile).$frame);
1804 }
1805 if ($this->imageMagickConvert_forceFileNameBody) {
1806 $theOutputName = $this->imageMagickConvert_forceFileNameBody;
1807 $this->imageMagickConvert_forceFileNameBody='';
1808 }
1809 $output = $this->tempPath.$this->filenamePrefix.$theOutputName.'.'.$newExt;
1810 $GLOBALS['TEMP_IMAGES_ON_PAGE'][]=$output;
1811
1812 if (!$this->file_exists_typo3temp_file($output,$imagefile) || $this->dontCheckForExistingTempFile) {
1813 $this->imageMagickExec($imagefile.$frame,$output,$command);
1814 }
1815 if (@file_exists($output)) {
1816 $info[3] = $output;
1817 $info[2] = $newExt;
1818 if ($params) { // params could realisticly change som imagedata!
1819 $info=$this->getImageDimensions($info[3]);
1820 }
1821 if ($info[2]==$this->gifExtension && !$this->dontCompress) {
1822 t3lib_div::gif_compress($info[3],''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
1823 }
1824 return $info;
1825 }
1826 }
1827 }
1828 }
1829
1830 /**
1831 * Gets the input image dimensions.
1832 *
1833 * @param string The image filepath
1834 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
1835 * @see imageMagickConvert(), tslib_cObj::getImgResource()
1836 */
1837 function getImageDimensions($imageFile) {
1838 ereg('([^\.]*)$',$imageFile,$reg);
1839 if (@file_exists($imageFile) && t3lib_div::inList($this->imageFileExt,strtolower($reg[0]))) {
1840 if ($returnArr = $this->getCachedImageDimensions($imageFile)) {
1841 return $returnArr;
1842 } else {
1843 if ($temp = @getImageSize($imageFile)) {
1844 $returnArr = Array($temp[0], $temp[1], strtolower($reg[0]), $imageFile);
1845 } else {
1846 $returnArr = $this->imageMagickIdentify($imageFile);
1847 }
1848 if($returnArr) {
1849 $this->cacheImageDimensions($returnArr);
1850 return $returnArr;
1851 }
1852 }
1853 }
1854 return false;
1855 }
1856
1857 /**
1858 * Cache the result of the getImageDimensions function into the database. Does not check if the
1859 * file exists!
1860 *
1861 * @param array $identifyResult: Result of the getImageDimensions function
1862 * @return boolean True if operation was successful
1863 * @author Michael Stucki <mundaun@gmx.ch> / Robert Lemke <rl@robertlemke.de>
1864 */
1865 function cacheImageDimensions($identifyResult) {
1866 global $TYPO3_DB;
1867 // Create a md5 hash of the filename
1868 if (function_exists('md5_file')) {
1869 $md5Hash = md5_file($identifyResult[3]);
1870 } else {
1871 $md5Hash = md5 (t3lib_div::getURL($identifyResult[3]));
1872 }
1873 if ($md5Hash) {
1874 $fieldArr = array (
1875 'md5hash' => $md5Hash,
1876 'md5filename' => md5($identifyResult[3]),
1877 'tstamp' => time(),
1878 'filename' => $identifyResult[3],
1879 'imagewidth' => $identifyResult[0],
1880 'imageheight' => $identifyResult[1],
1881 );
1882 $TYPO3_DB->exec_INSERTquery('cache_imagesizes', $fieldArr);
1883 if (!$err = $TYPO3_DB->sql_error()) {
1884 return true;
1885 }
1886 }
1887 return false;
1888 }
1889
1890 /**
1891 * Fetch the cached imageDimensions from the MySQL database. Does not check if the image file exists!
1892 *
1893 * @param string The image filepath
1894 * @return array Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
1895 * @author Michael Stucki <mundaun@gmx.ch> / Robert Lemke <rl@robertlemke.de>
1896 */
1897 function getCachedImageDimensions($imageFile) {
1898 global $TYPO3_DB;
1899 // Create a md5 hash of the filename
1900 if(function_exists('md5_file')) {
1901 $md5Hash = md5_file($imageFile);
1902 } else {
1903 $md5Hash = md5(t3lib_div::getURL ($imageFile));
1904 }
1905 ereg('([^\.]*)$',$imageFile,$reg);
1906 $res = $TYPO3_DB->exec_SELECTquery ('md5hash, imagewidth, imageheight', 'cache_imagesizes', 'md5filename="'.md5($imageFile).'"');
1907 if ($res) {
1908 if ($row = $TYPO3_DB->sql_fetch_assoc($res)) {
1909 if ($row['md5hash']!=$md5Hash) {
1910 // file has changed, delete the row
1911 $TYPO3_DB->exec_DELETEquery ('cache_imagesizes', 'md5hash="'.$TYPO3_DB->quoteStr($row['md5hash']).'"');
1912 } else {
1913 return (array($row['imagewidth'], $row['imageheight'], strtolower($reg[0]), $imageFile));
1914 }
1915 }
1916 }
1917 return false;
1918 }
1919
1920 /**
1921 * Get numbers for scaling the image based on input
1922 *
1923 * @param array Current image information: Width, Height etc.
1924 * @param integer "required" width
1925 * @param integer "required" height
1926 * @param array Options: Keys are like "maxW", "maxH", "minW", "minH"
1927 * @return array
1928 * @access private
1929 * @see imageMagickConvert()
1930 */
1931 function getImageScale($info,$w,$h,$options) {
1932 if (strstr($w.$h, 'm')) {$max=1;} else {$max=0;}
1933 $w=intval($w);
1934 $h=intval($h);
1935 // if there are max-values...
1936 if ($options['maxW']) {
1937 if ($w) { // if width is given...
1938 if ($w>$options['maxW']) {
1939 $w=$options['maxW'];
1940 $max=1; // height should follow
1941 }
1942 } else {
1943 if ($info[0]>$options['maxW']) {
1944 $w=$options['maxW'];
1945 $max=1; // height should follow
1946 }
1947 }
1948 }
1949 if ($options['maxH']) {
1950 if ($h) { // if height is given...
1951 if ($h>$options['maxH']) {
1952 $h=$options['maxH'];
1953 $max=1; // height should follow
1954 }
1955 } else {
1956 if ($info[1]>$options['maxH']) { // Changed [0] to [1] 290801
1957 $h=$options['maxH'];
1958 $max=1; // height should follow
1959 }
1960 }
1961 }
1962 $out['origW']=$w;
1963 $out['origH']=$h;
1964 $out['max'] = $max;
1965
1966 if (!$this->mayScaleUp) {
1967 if ($w>$info[0]){$w=$info[0];}
1968 if ($h>$info[1]){$h=$info[1];}
1969 }
1970 if ($w || $h) { // if scaling should be performed
1971 if ($w && !$h) {
1972 $info[1] = ceil($info[1]*($w/$info[0]));
1973 $info[0] = $w;
1974 }
1975 if (!$w && $h) {
1976 $info[0] = ceil($info[0]*($h/$info[1]));
1977 $info[1] = $h;
1978 }
1979 if ($w && $h) {
1980 if ($max) {
1981 $ratio = $info[0]/$info[1];
1982 if ($h*$ratio > $w) {
1983 $h = round($w/$ratio);
1984 } else {
1985 $w = round($h*$ratio);
1986 }
1987 }
1988 $info[0] = $w;
1989 $info[1] = $h;
1990 }
1991 }
1992 $out[0]=$info[0];
1993 $out[1]=$info[1];
1994 // Set minimum-measures!
1995 if ($options['minW'] && $out[0]<$options['minW']) {
1996 if ($max && $out[0]) {
1997 $out[1]= round($out[1]*$options['minW']/$out[0]);
1998 }
1999 $out[0]=$options['minW'];
2000 }
2001 if ($options['minH'] && $out[1]<$options['minH']) {
2002 if ($max && $out[1]) {
2003 $out[0]= round($out[0]*$options['minH']/$out[1]);
2004 }
2005 $out[1]=$options['minH'];
2006 }
2007
2008 return $out;
2009 }
2010
2011 /**
2012 * Used to check if a certain process of scaling an image is already being carried out (can be logged in the SQL database)
2013 *
2014 * @param string Output imagefile
2015 * @param string Original basis file
2016 * @return boolean Returns true if the file is already being made; thus "true" means "Don't render the image again"
2017 * @access private
2018 */
2019 function file_exists_typo3temp_file($output,$orig='') {
2020 if ($this->enable_typo3temp_db_tracking) {
2021 if (@file_exists($output)) { // If file exists, then we return immediately
2022 return 1;
2023 } else { // If not, we look up in the cache_typo3temp_log table to see if there is a image being rendered right now.
2024 $md5Hash=md5($output);
2025 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_typo3temp_log', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($md5Hash, 'cache_typo3temp_log').'" AND tstamp>'.(time()-30));
2026 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { // If there was a record, the image is being generated by another proces (we assume)
2027 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...)
2028 if (is_object($GLOBALS['TT'])) $GLOBALS['TT']->setTSlogMessage('typo3temp_log: Assume this file is being rendered now: '.$output);
2029 return 2; // Return 'success - 2'
2030 } 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.
2031
2032 $insertFields = array(
2033 'md5hash' => $md5Hash,
2034 'tstamp' => time(),
2035 'filename' => $output,
2036 'orig_filename' => $orig
2037 );
2038 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_typo3temp_log', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($md5Hash, 'cache_typo3temp_log').'"');
2039 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_typo3temp_log', $insertFields);
2040
2041 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);
2042 return 0;
2043 }
2044 }
2045 } else {
2046 return @file_exists($output);
2047 }
2048 }
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067 /***********************************
2068 *
2069 * ImageMagick API functions
2070 *
2071 ***********************************/
2072
2073 /**
2074 * Returns an array where [0]/[1] is w/h, [2] is extension and [3] is the filename.
2075 * Using ImageMagick
2076 *
2077 * @param string The absolute image filepath
2078 * @return array
2079 */
2080 function imageMagickIdentify($imagefile) {
2081 if (!$this->NO_IMAGE_MAGICK) {
2082 $cmd = $this->imageMagickPath.'identify '.$this->wrapFileName($imagefile);
2083 exec($cmd, $returnVal);
2084 $splitstring=$returnVal[0];
2085 $this->IM_commands[] = Array ('identify',$cmd,$returnVal[0]);
2086 if ($splitstring) {
2087 ereg('([^\.]*)$',$imagefile,$reg);
2088 $splitinfo = explode(' ', $splitstring);
2089 while (list($key,$val) = each($splitinfo)) {
2090 $temp = '';
2091 if ($val) {$temp = explode('x', $val);}
2092 if (intval($temp[0]) && intval($temp[1])) {
2093 $dim=$temp;
2094 break;
2095 }
2096 }
2097 if ($dim[0] && $dim[1]) {
2098 return Array($dim[0], $dim[1], strtolower($reg[0]), $imagefile);
2099 }
2100 }
2101 }
2102 }
2103
2104 /**
2105 * Executes a ImageMagick "convert" on two filenames, $input and $output using $params before them.
2106 * Can be used for many things, mostly scaling and effects.
2107 *
2108 * @param string The absolute image filepath, input file (read from)
2109 * @param string The absolute image filepath, output filename (written to)
2110 * @param string ImageMagick parameters
2111 * @return string The result of a call to PHP function "exec()"
2112 */
2113 function imageMagickExec($input,$output,$params) {
2114 if (!$this->NO_IMAGE_MAGICK) {
2115 $cmd = $this->imageMagickPath.'convert '.$params.' '.$this->wrapFileName($input).' '.$this->wrapFileName($output);
2116 $this->IM_commands[] = Array ($output,$cmd);
2117 return exec($cmd);
2118 }
2119 }
2120
2121 /**
2122 * 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)
2123 * Can be used for many things, mostly scaling and effects.
2124 *
2125 * @param string The absolute image filepath, bottom file
2126 * @param string The absolute image filepath, overlay file (top)
2127 * @param string The absolute image filepath, the mask file (grayscale)
2128 * @param string The absolute image filepath, output filename (written to)
2129 * @return void
2130 */
2131 function combineExec($input,$overlay,$mask,$output) {
2132 if (!$this->NO_IMAGE_MAGICK) {
2133 $cmd = $this->imageMagickPath.$this->combineScript.' -compose over '.$this->wrapFileName($input).' '.$this->wrapFileName($overlay).' '.$this->wrapFileName($mask).' '.$this->wrapFileName($output);
2134 $this->IM_commands[] = Array ($output,$cmd);
2135 exec($cmd);
2136 }
2137 }
2138
2139 /**
2140 * Wrapping the input filename in double-quotes
2141 *
2142 * @param string Input filename
2143 * @return string The output wrapped in "" (if there are spaces in the filepath)
2144 * @access private
2145 */
2146 function wrapFileName($inputName) {
2147 if (strstr($inputName,' ')) {
2148 $inputName='"'.$inputName.'"';
2149 }
2150 return $inputName;
2151 }
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175 /***********************************
2176 *
2177 * Various IO functions
2178 *
2179 ***********************************/
2180
2181 /**
2182 * Returns true if the input file existed
2183 *
2184 * @param string Input file to check
2185 * @return string Returns the filename if the file existed, otherwise empty.
2186 */
2187 function checkFile($file) {
2188 if (@is_file($file)) {
2189 return $file;
2190 } else {
2191 return '';
2192 }
2193 }
2194
2195 /**
2196 * 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.
2197 *
2198 * @param pointer The image pointer (reference)
2199 * @param string The ImageMagick parameters. Like effects, scaling etc.
2200 * @return void
2201 */
2202 function applyImageMagickToPHPGif(&$im, $command) {
2203 $tmpStr = $this->randomName();
2204 $theFile = $tmpStr.'.'.$this->gifExtension;
2205 $this->ImageGif($im, $theFile);
2206 $this->imageMagickExec($theFile,$theFile,$command);
2207 $tmpImg = $this->imageCreateFromGif($theFile);
2208 if ($tmpImg) {
2209 ImageDestroy($im);
2210 $im = $tmpImg;
2211 $this->w = imagesx($im);
2212 $this->h = imagesy($im);
2213 }
2214 if (!$this->dontUnlinkTempFiles) {
2215 unlink($theFile);
2216 }
2217 }
2218
2219 /**
2220 * 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.
2221 * For example: If the number of pixels exceeds $this->pixelLimitGif (normally 10000) then it will be a "jpg" string in return.
2222 *
2223 * @param string The file extension, lowercase.
2224 * @param integer The width of the output image.
2225 * @param integer The height of the output image.
2226 * @return string The filename, either "jpg" or "gif"/"png" (whatever $this->gifExtension is set to.)
2227 */
2228 function gif_or_jpg($type,$w,$h) {
2229 if ($type=='ai' || $w*$h < $this->pixelLimitGif) {
2230 return $this->gifExtension;
2231 } else {
2232 return 'jpg';
2233 }
2234 }
2235
2236 /**
2237 * Writing the internal image pointer, $this->im, to file based on the extension of the input filename
2238 * Used in GIFBUILDER
2239 * Uses $this->setup['reduceColors'] for gif/png images and $this->setup['quality'] for jpg images to reduce size/quality if needed.
2240 *
2241 * @param string The filename to write to.
2242 * @return string Returns input filename
2243 * @see tslib_gifBuilder::gifBuild()
2244 */
2245 function output($file) {
2246 if ($file) {
2247 ereg('([^\.]*)$',$file,$reg);
2248 $ext=strtolower($reg[0]);
2249 switch($ext) {
2250 case $this->gifExtension:
2251 if ($this->ImageGif($this->im, $file)) {
2252 // ImageMagick operations
2253 if($this->setup['reduceColors']) {
2254 $this->imageMagickExec($file,$file,' -colors '.t3lib_div::intInRange($this->setup['reduceColors'],2,255));
2255 t3lib_div::gif_compress($file,''); // Compress with IM (lzw) or GD (rle) (Workaround for the absence of lzw-compression in GD)
2256 } else {
2257 t3lib_div::gif_compress($file, 'IM'); // Compress with IM! (adds extra compression, LZW from ImageMagick) (Workaround for the absence of lzw-compression in GD)
2258 }
2259 }
2260 break;
2261 case 'jpg':
2262 case 'jpeg':
2263 $tmpStr = $this->randomName();
2264 $theFile = $tmpStr.'.'.$this->gifExtension;
2265 if ($this->ImageGif($this->im, $theFile)) {
2266 // ImageMagick operations
2267 $operations='';
2268 if($this->setup['quality']) {
2269 $operations.=' -quality '.t3lib_div::intInRange($this->setup['quality'],10,100);
2270 }
2271 $this->imageMagickExec($theFile,$file,$operations);
2272 if (!$this->dontUnlinkTempFiles) {
2273 unlink($theFile);
2274 }
2275 }
2276 break;
2277 }
2278 $GLOBALS['TEMP_IMAGES_ON_PAGE'][]=$file;
2279 }
2280 return $file;
2281 }
2282
2283 /**
2284 * Destroy internal image pointer, $this->im
2285 *
2286 * @return void
2287 * @see tslib_gifBuilder::gifBuild()
2288 */
2289 function destroy() {
2290 ImageDestroy($this->im);
2291 }
2292
2293 /**
2294 * Returns Image Tag for input image information array.
2295 *
2296 * @param array Image information array, key 0/1 is width/height and key 3 is the src value
2297 * @return string Image tag for the input image information array.
2298 */
2299 function imgTag ($imgInfo) {
2300 return '<img src="'.$imgInfo[3].'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'" border="0" alt="" />';
2301 }
2302
2303 /**
2304 * Writes the input GDlib image pointer to file
2305 *
2306 * @param pointer The GDlib image resource pointer
2307 * @param string The filename to write to
2308 * @return mixed The output of either imageGif or imagePng based on whether the $this->gifExtension was set to "gif" or "png"
2309 * @see maskImageOntoImage(), scale(), output()
2310 */
2311 function ImageGif($destImg, $theImage) {
2312 imageinterlace ($destImg,0);
2313 if ($this->gifExtension=='gif') {
2314 return ImageGif($destImg, $theImage);
2315 }
2316 if ($this->gifExtension=='png') {
2317 return ImagePng($destImg, $theImage);
2318 }
2319 }
2320
2321 /**
2322 * Creates a new GDlib image resource based on the input image filename.
2323 * If it fails creating a image from the input file a blank gray image with the dimensions of the input image will be created instead.
2324 *
2325 * @param string Image filename
2326 * @return pointer Image Resource pointer
2327 */
2328 function imageCreateFromGif($sourceImg) {
2329 $imgInf = pathinfo($sourceImg);
2330 $ext = strtolower($imgInf['extension']);
2331
2332 // if ($ext=='gif' && (ImageTypes() & IMG_GIF)) {
2333 if ($ext=='gif' && function_exists('imagecreatefromgif')) {
2334 return imageCreateFromGif($sourceImg);
2335 }
2336 // if ($ext=='png' && (ImageTypes() & IMG_PNG)) {
2337 if ($ext=='png' && function_exists('imagecreatefrompng')) {
2338 return imageCreateFromPng($sourceImg);
2339 }
2340 // if (($ext=='jpg' || $ext=='jpeg') && (ImageTypes() & IMG_JPG)) {
2341 if (($ext=='jpg' || $ext=='jpeg') && function_exists('imagecreatefromjpeg')) {
2342 return imageCreateFromJpeg($sourceImg);
2343 }
2344
2345 // If non of the above:
2346 $i = @getimagesize($sourceImg);
2347 $im = imagecreate($i[0],$i[1]);
2348 ImageColorAllocate($im, 128,128,128);
2349 return $im;
2350 }
2351 }
2352
2353
2354 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_stdgraphic.php']) {
2355 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_stdgraphic.php']);
2356 }
2357 ?>